Next.js Discord

Discord Forum

Authenticating in layout. Is it a good idea?

Unanswered
Rhinelander posted this in #help-forum
Open in Discord
Avatar
RhinelanderOP
I am authenticating users in the layout with session retrieval function that i cache with react cache. But i still get 2 session retrievals after refresh

6 Replies

Avatar
Oak apple gall wasp
No, not even in middleware.

Why? Because it slows down staff. For each request, you need to authenticate the user, even when it’s unnecessary.

It would be better to authenticate the user for the specific path they want to access.

For example, if you want to authorize a user for the admin or settings page, you can implement that directly on those paths.
Avatar
RhinelanderOP
What about if i authenticate in navbar and in certain page i make 2 requests
i tried caching it with react cache but it still makes 2 requests (4 in the terminal dev mode)
Avatar
Barbary Lion
what if you check only in protected routes for auth in middleware?
Avatar
Oak apple gall wasp
The thing is it depends on your usecase, if you have only 1-2 protected route sure
Avatar
RhinelanderOP
I have many protected routes... I don't want to use middleware to do it