↳ See other learning resources
Next Auth with Next.js
This guide assumes you use the app router and will use the Google OAuth provider.
npm i next-auth- Create a Google cloud project, go to console.cloud.google.com/apis/credentials
- If available, click configure consent screen. After going through the process, go to scopes and add
auth/userinfo.emailandauth/userinfo.profile - Create two clients, both web applications. One is local with URL
http://localhost:3000and Authorized redirect URIs set tohttp://localhost:3000/api/auth/callback/googleand the other ishttps://yourdomain.comandhttps://yourdomain.com/api/auth/callback/google
- If available, click configure consent screen. After going through the process, go to scopes and add
- Add to .env:
NEXTAUTH_URL=http://localhost:3000 #change to yourdomain.com in the production environment
NEXTAUTH_SECRET=[generate a random code using `openssl rand -base64 32`]
NEXT_PUBLIC_GOOGLE_CLIENT_ID=...apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=...
- create
app/api/[...nextauth]/route.tswith the following:
import NextAuth, { AuthOptions } from "next-auth";
import GoogleProvider from 'next-auth/providers/google';
export const authOptions: AuthOptions={
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
allowDangerousEmailAccountLinking: true
})
]
};
const handler=NextAuth(authOptions);
export { handler as GET, handler as POST };