Next.js Discord

Discord Forum

How to handle redirects depending on LocalStorage?

Answered
White-horned horntail posted this in #help-forum
Open in Discord
Avatar
White-horned horntailOP
There are a few pages in my Next app that shouldn't be loaded if there are some values missing in LocalStorage. For example, /buy should not be loaded if localStorage does not have the key verified, and should be redirected to /signup instead.

I considered using middleware, but that runs on the server, and won't have access to localStorage. What is the ideal way to solve this? I am using App Router.
Answered by Ray
try to use cookies instead or do it on client side if you need to use localStorage
View full answer

9 Replies

Avatar
Ray
try to use cookies instead or do it on client side if you need to use localStorage
Answer
Avatar
White-horned horntailOP
Is there a way to do it in the client side without putting the redirection logic in the page?
For example, we have one metadata.ts file that contains all the redirection logic if we want to do it in the server side. Is it possible to have all the redirection logic in one file for the client side too?
Avatar
Ray
no, if you are using localStorage in metadata.ts
Avatar
White-horned horntailOP
Okay, thanks.
Avatar
Komondor
I'm pretty sure any user can edit the values in LocalStorage, so I would be cautious about using that to prevent access from certain pages
Avatar
Asian black bear
A common technique is to wrap the cookie with iron-webcrypto or even using iron-session
Users can look at cookies too, they are just harder for malicious JS to see if properly configured. In either case, iron is a pretty good way to handle it.
Avatar
White-horned horntailOP
I know. The value they use will still be validated in the backend. But for the frontend to work, I am using the localStorage. My use case is a bit more convoluted, so I overly simplified it.