Next.js Discord

Discord Forum

Best solution for Auth w/ JWT token?

Answered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hey everyone,

Working with Next 14 and a lot of the app is in server components. We are pulling in data via the Wordpress REST API, which works great so far. Client wants to be able to login to the app via Wordpress as well and authorize certain things that way.

My question is, if I'm able to get a JWT from Wordpress, how best to integrate this into Next? Not sure if this would even have anything to do with NextAuth.

Ideally, we'd hit another endpoint once the user is logged in to get any pertinent info we need about the user.

thank you!
Answered by Blue orchard bee
I've implemented myself external-JWT implementations with Next-Auth, although a bit confusing at first, works fairly well.
View full answer

14 Replies

Blue orchard bee
I've implemented myself external-JWT implementations with Next-Auth, although a bit confusing at first, works fairly well.
Answer
Blue orchard bee
Spectacled bearOP
ok great, thank you @Blue orchard bee any particular gotchas you remember?
thinking it should be cut and dry once I get the token
Blue orchard bee
Yes! Modifying the next-auth.d.ts according to what you expect to receive saves you so many headaches with TypeScript.
This is a common setup for me.
declare module 'next-auth' {
  // These types tell TypeScript
  // you're passing down JWT to the client 
  interface User {
    email: string;
    jwt: string;
  }

  interface Token {
    email: string;
    jwt: string;
  }

  interface Session {
    jwt: string;

    user: {
      email: string;
      // ...user data you want to 
      // pass to the client
    }
  }
}
Some of it is confusing but once you understand a bit what Next-Auth is doing behind the scenes it makes a bit more sense.
Spectacled bearOP
great, appreciate that
I see the article you linked is for pages router, assume app router works as well?
Blue orchard bee
Yes it mostly differentiates in setup, but library implementation should be the same.
They have initialization and installation covered for App router too in their site.
Spectacled bearOP
really appreciate this, thank you!
Blue orchard bee
No problem :D