Due to the lack of specific documentation on how to use NextAuth.js with the Next.js app router as of the current date (2023ā11ā29), the following information provides some supplementary guidance
reference:
import SessionProvider
Due to Next.js app routerās default behavior where all components under the directory are React Server Components, NextAuth.js cannot be directly used with the browser-cached SessionProvider. There are two methods to load the SessionProvider:
- Create an
authProvider.tsx
component and declare 'use client' at the top of this component. Import this component inlayout.tsx
. - Import the SessionProvider in the nearest common client component used by all components that require authentication status and wrap that common component with it.
Here are the implementation codes for both methods:
method 1
// src/app/AuthProvider.tsx
import { SessionProvider } from 'next-auth/react'
export defalut function AuthProvider({ children }:{ children:Reacr.ReactNode }) {
return (
<SessionProvider>
{children}
</SessionProvider>
)
}
// app/src/layout.tsx
import AuthProvider from './AuthProvider'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>
<AuthProvider>
{children}
</AuthProvider>
</body>
</html>
)
}
āThis method is not recommended. Although it does work, it breaks the default server component of nextjs.
method 2
// src/app/page.tsx
import { SessionProvider } from 'next-auth/react'
export default function Page() {
return (
<SessionProvider>
// other child component
</SessionProvider>
)
}
set api
Due to certain changes in the api setting rules of nextjs app router, the original documentās api setting method based on page router also needs to be modified to some extent.
// src/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import { authOptions } from "@/conf/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
// src/conf/auth.ts
import { NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
export const authOptions: NextAuthOptions = {
// Configure one or more authentication providers
// TODO: Occasionally bug(https://github.com/nextauthjs/next-auth/discussions/3186)
providers: [
GithubProvider({
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_SECRET_ID as string,
}),
],
secret: process.env.NEXTAUTH_SECRET as string,
};
Some people here may wonder why auth.ts should be written in a separate file. If your project is deployed on vercel, writing authOptions and api together may cause a build error:
Although I donāt know whatās going on yet, writing authOptions and api separately can avoid the above problems ą² _ą²
After completing the above two steps, you can refer to the official documentation to continue coding!