Next.js Discord

Discord Forum

Best Practice for Implementing JWT Auth

Answered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
I am extremely new to NextJS, I am trying to figure out what the best possible way to implement JWT Auth into my application is.

The method I am currently seems like it can work, but doesn't feel like best practice.

As of right now, my client-side login function sets a cookie
setCookie('jwtToken', token);


Then my server's middleware.ts (which is matched to all authenticated routes), I grab the token from the cookies and perform checks inside the Middleware.
export function middleware(request: NextRequest) {
  if (!tokenChecks(token)) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next();
}


However, my concern is that the docs warn against running any database checks within middleware.
- How would be best to begin implementing authorization checks on certain pages?
- What are some general design principles I should keep in mind while doing this?
- Are there any security-related pitfalls I should be avoiding here?
Answered by !=tgt
middleware's not that bad of an idea and it's pretty common
View full answer

12 Replies

middleware's not that bad of an idea and it's pretty common
Answer
next-auth and other libs use middleware for checking auth
However, my concern is that the docs warn against running any database checks within middleware.
where is this
eh
wait
wait
for jwt you could just check if the token's valid in middleware
and then check the exact user and stuff and redir further down in a layout or page
Northeast Congo LionOP
That works for almost everything for me. It is great for API routes. The only concern I have is restricting via appRouter. If it is a static route, how would I block a user from having access to certain routes?
because the page code runs client side