Search code examples
cookiesnext.jstokennext-auth

How to manage tokens with next-auth


I've been working on both backend / frontend lately. I'm building a simple note-taking application, and I have a question about the login process.

I'm using the next.js app directory, and I'm trying to use google oauth login with next-auth. I was wondering how to manage the token in this process.

In other blogs, you mention 'cookies' and 'local-storage' a lot. But I'm using express on the backend, and I want to store the access_token in the db.

Here is the code

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID ?? '',
      clientSecret: process.env.GOOGLE_SECRET ?? '',
    }),
  ],
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
    updateAge: 24 * 60 * 60, // 24 hours
  },

  secret: process.env.NEXTAUTH_SECRET,

  callbacks: {
    async signIn({ user, account }) {
      const dataToSend = {
        user: {
          ...user,
          accessToken: account?.access_token,
          expires: account?.expires_at,
        },
      };

      const res = await fetch(
        `${process.env.NEXT_PUBLIC_SERVER_URL}/api/user`,
        {
          method: 'POST',
          body: JSON.stringify(dataToSend),
        },
      );

      if (!res.ok) {
        console.error('error!');
        return false;
      }

      return true;
    },

    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token;
      }

      return token;
    },

    async session({ session, token }) {
      session.user = token as any;

      return session;
    },
  },
};

Here we use jwt and session to get access_token from client or server with 'useSession hooks'. I can also put the access_token in the server db when signing in.

When we send the request, we put 'session.user.access_Token' in the header with authorization.

But I have a problem, I don't know what to do with the refresh token, whenever I sign in, the token is sent and the expires time keeps updating, i.e. whenever I sign in, the token keeps updating.

Is this the right way to do it? If there is another way, please let me know.

Additionally, when I use next-auth, it looks like I have a prisma adapter.

After using prisma adapter on login to save data directly to DB,

When accessToken is needed, the client gets the token with the useSession hook, and the backend compares it with the token stored in the DB and authorizes the request?

PrismaAdapter()


Solution

  • Reply to what I wrote. I'm using DB on my express server, but I changed it to not store the token in DB.

    Instead, I installed next-auth as a package on express as well. And when the client requests the API, if you look at the cookie, it sends the next-auth-token.

    And the express server decrypts this token. For this, we use the getToken function. This can be imported from the next-auth lib.

    next-auth getToken

    Hopefully, you won't have to go through the same trial and error as I did.