Next.js Discord

Discord Forum

Is authentication in layout.js safe?

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
Im using the new App Router version of nextjs. I want to protect a whole subset of routes using authentication, so I'm thinking of putting auth logic in a layout.js.

Is this safe? Or should I add an auth check for each page individually?

6 Replies

For a better performance, we normally put auth logic in middleware. You can receive the request, read cookies/headers, and modify/return a response in middleware.
Middleware can protect all the routes, including route handlers while layout can’t.
And back to your original question: Yes, although layout won’t be rerendered, it’s rendered every time the user opens it if it has dynamic functions invoked, such as cookies.
Brown bearOP
Thanks for the reply. I'll look into middleware!
@fuma Middleware can protect all the routes, including route handlers while layout can’t.
Brown bearOP
Sorry - can you clarify why layout can't protect all the routes? Will it not protect the child routes?
It only protect its child route, but not route handlers/parent routes