Search code examples
typescriptgithubnext.jsgithub-apinext-auth

Next-auth get token for Github REST API


I want to implement user login and access some user data via the Github REST API (eg. repository, issues).

Then I successfully implemented a login feature, but the Github REST API requires a token to access its endpoints. I checked the session using getServerSession(authOptions) and obtained some information, but not the token (as shown below).

"session": {
  "user": {
    "name": "UserName",
    "email": "[email protected]",
    "image": "https://xxxxxx.xxxxxx/xxxxx"
  }
}

I tried some solutions on StackOverflow but none of them worked for me.
Is there somebody who can help me? Thansk.


Solution

  • I found a solution in next.js Discrod server by someone's help.
    docs: https://next-auth.js.org/configuration/callbacks#sign-in-callback

    export const authOptions : NextAuthOptions = {
      adapter: ...,
      session: {
        strategy: "jwt", // add this
      },
      providers: [...],
      // add two callback functions following
      callbacks: {
        async session({ session, token, user }) {
          session.accessToken = token.accessToken as string;
          return session;
        },
        async jwt({ token, user, account, profile }) {
          if (account) {
            token.accessToken = account.access_token;
          }
          return token;
        }
      },
    };
    

    Then for typescript, you need to write this in "types/next-auth.d".
    docs: https://next-auth.js.org/getting-started/typescript

    import NextAuth, { DefaultSession } from "next-auth";
    
    declare module "next-auth" {
      interface Session {
        accessToken: string;
        expires: string;
        user: {
          address: string
        } & DefaultSession["user"];
      }
    }