Next.js Discord

Discord Forum

How to use middleware to check if a user has permission to go into a page or not? Can I do SSR?

Unanswered
Vikhan posted this in #help-forum
Open in Discord
VikhanOP
Hi! I have a nextjs project with a laravel backend. Im using spatie permission library in the backend which is great.

Now I want to know how to use the nextjs middleware to perform requests and see if a user is allowed to be in a page or not.

I was thinking of two options: middlewares (if its possible?), or a server side page component that performs a request to the server and checks if a user has the permission or not in the backend/database (with this I mean, the top component of a page is server side to check permissions, then client side child components if needed).

How would you handle this?

7 Replies

Now I want to know how to use the nextjs middleware to perform requests and see if a user is allowed to be in a page or not.

Yes you can use fetch in middleware but keep in mind that the middleware is supposed to be lightweight.

You can make a HOC function that wraps your route or
create a reusable auth guard funciton that you can use in page.js/layout.js
How would you handle this?
Definetly 3 ways:
1. check in middleware
2. check in every layout & page & route & server action
3. check in client side (using useEffect to check for auth status)

These 3 can be done with NextAuth and yes, nextauth can integrate to custom backend
VikhanOP
Roger that, thank you
Im using laravel though as my backend
So I have the laravel sanctum auth system already up
With spatie roles and permissions
i see