Back to blogs
Loading article…
Blog
Longer posts — published here first, then cross-posted to Dev.to with a canonical URL back to this site.
Back to blogs
Back to blogs
Postnextjs, authjs, typescript, github
Modify your nextauth client and add a callbacks section that will get the access token from the...
Date published

You can select the scopes you want to request from GitHub/your oauthprovider in the login page, and...

Why You Might Still Pick Next.js Over TanStack Start From a TanStack Start...

A guide to creating Android home screen widgets using Expo modules, complete with state management,...
Modify your nextauth client and add a callbacks section that will
1import NextAuth from "next-auth";2import GitHub from "next-auth/providers/github";34export const githubScopes = ["user", "repo", "delete_repo"] as const;56export const { handlers, signIn, signOut, auth } = NextAuth({7 pages: {8 signIn: "/auth",9 },10 providers: [11 GitHub({12 authorization: {13 params: {14 scope: githubScopes.slice(0, -2).join(" "),15 },16 },17 // @ts-expect-error18 async profile(profile) {19 return { ...profile } // get the user oauth profile20 },21 }),22 ],23 debug: true,24 callbacks: {25 jwt: async ({ token, user,account }) => {26 if (account) {27 token.accessToken = account.access_token;28 }29 if (user) {30 token.user = user; // Include the full user profile in the token31 }32 return token;3334 },35 session: async ({ session, token }) => {36 // @ts-expect-error37 session.accessToken = token.accessToken; // Include the access token in the session38 // @ts-expect-error39 session.user = token.user;40 return session;4142 },43 authorized: async ({ auth }) => {44 // Logged in users are authenticated, otherwise redirect to login page45 return !!auth;46 },47 async redirect({ url, baseUrl }) {48 // redirect to the dashboard if the user is signed in49 return `${baseUrl}/dashboard`;50 },51 },52});53
to fix the types create a next-auth.d.ts file
1// next-auth.d.ts2import "next-auth";3import { DefaultSession } from "next-auth";45declare module "next-auth" {6 /**7 * Extends the `Session` interface to include custom fields.8 * This is merged with the default `Session` type from NextAuth.js.9 */10 interface Session {11 accessToken?: string;12 user: GithubUser & DefaultSession["user"]; // Merge with default user fields13 }14}1516export type GithubUser={17 login: string18 id: string19 node_id: string20 avatar_url: string21 gravatar_id: string22 url: string23 html_url: string24 followers_url: string25 ....other fie;lds26}27