I'm using next middleware to do protected routes and I'm using cookies to do the checking since you can use cookies on the server-side.
When a user logged in, I save the info on local storage(for all my frontend auth checks) and a cookie set to true if logged in(for server-side checking).
The issue is that when im on mobile, and a user logs in, the info is saved successfully. But if the user closes the browser(like safari) then opens it again and goes to the site, the user is still logged in but the Cookie doesnt seem to work(or is no longer there) but the localstorage still is there. Then this causes a case where the user is logged in but they cant access the logged in(protected) routes.
The following is my login in function
let loginUser = async (e) => {
e.preventDefault();
let response = await fetch(URL, {
method:'POST',
headers:{
'Content-Type': 'application/json'
},
body:JSON.stringify({'email':e.target.email.value, 'password':e.target.password.value})
})
if(response.ok){
let data = await response.json();
setAuthTokens(data);
localStorage.setItem("authTokens", JSON.stringify(data));
Cookies.set("auth", "true");
setUser(true);
setFailed(false);
router.push("/dashboard");
} else {
setFailed(true)
}
}
The following is my middleware
export default function middleware(req, event) {
let verify = req.cookies['auth']
const url = req.url
if (url.includes("/login") || url.includes("/signup")) {
if (verify) {
return NextResponse.redirect("some_url/dashboard");
}
}
if (url == "some_url" && verify) {
return NextResponse.redirect("some_url/dashboard");
}
if(url.includes("/dashboard")){
if(!verify){
return NextResponse.redirect("some_url/login");
}
}
}
This code may cause some security issues so I suggest you to set cookie from server also have an API for logout that clears cookie.
BTW if you don't set expire date in your cookie safari mobile will remove it.
You can do this by passing options to third argument of Cookies.set() .
It would be something like this:
Cookies.set('auth', 'true', { expires: 7 }); //expires 7 days from now