Next.js Discord

Discord Forum

cookie authentication

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
i have two pages that require the user to be authenticated. i do this by checking and verifying an http only cookie. it looks like this:

app/
  layout.tsx
  page.tsx
  dashboard/
    page.tsx


currently i have the cookie check in layout.tsx but i noticed it doesn't happen on <Link> navigation, which is a problem for because i'd like the authentication check to happen on every navigation.

i was wondering if layout.tsx is the right spot to do the auth check or maybe that belongs somewhere else, like the template.tsx or middleware.ts files

4 Replies

Atlantic salmon
Root layout server code wont get executed on page change
So you can centralize auth in the middelware.ts function or even have a check in each page, whatever fits your needs the best
I think it is more common to do it on middleware tho
Barbary LionOP
i see. i think it's a bit of a confusing pattern to be able to pull cookies from a page, implying i can do cookie auth there but in actuality i should be doing from a middleware. middleware auth check IMO feels a bit less maintainable maybe.