Next.js Discord

Discord Forum

How to verify user's membership is still valid before accessing each page?

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Hey guys, I need help. This problem really bugs me out, and I have no clue what to do. So, each user in the database has a field called 'membership_expiration_date'. If the membership is expired, user will be redirected to the payment page. I tried to use middleware to achieve this goal, however middleware does not allow database call. I can verify the user's membership by checking if it's expired before each page load. However, this is very tedious and error-prone. Can anyone tell me any better way to do it?

16 Replies

My suggestion is to make the use of JWT tokens, you can store a jwt token containing the expire date in cookies and parse it in your middleware. It also brings a better performance by reducing database queries, and it’s how the general implement similar things.
Polar bearOP
I have thought about it. However, the issue is that the expiration date on the database might change
and JWT on the client side will have the old expiration date
this will be an synchronization or disparity issue
It depends on when it’s changed, for example, if it only changes after the user paid, you can update the jwt token.
Because if the middleware can’t perform database queries, you have to do it in somewhere else, currently here’s no an alternative for that.
So checking the membership in every page will be the only solution over all, unfortunately
Polar bearOP
how do you update the JWT token besides logging the users out and log them in again
?
In a route handler, or server action, you can read and set the cookies
Polar bearOP
yea the membership expiration date only only changes after the user pays
So you can just modify the jwt token
Polar bearOP
example?
i am not sure if you can modify jwt
I can’t give an example at the moment, I recommend searching for some examples online
@Polar bear i am not sure if you can modify jwt
Basically, you can parse the token, and set a new token via cookies().set in the server side
Technically, only your server can encode/decode jwt tokens, which makes sense to modify the token