How to verify user's access is still valid before accessing each page in next.js with nextauth?

391 Views Asked by At

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 as I will call edge function. 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?

1

There are 1 best solutions below

1
ndom91 On

Can you expand on this membership field a bit? That's not a default next-auth field, where is it coming from? What other services / libraries are you using?

You can check if the user's next-auth session is active with the useSession hook, check out an example here: https://authjs.dev/getting-started/oauth-tutorial#consuming-the-session-via-hooks

EDIT: If you've successfully modified the user table from the next-auth defaults, and saved the membership field(s) there, you will be able to access it via the useSession hook I mentioned above.

For example:

const { data: session, status } = useSession()
const userMembership = session?.user?.membership