How to setup Next-Auth in a Next.js app
Create a Next.js project with javaScript, Tailwind and app router
Install NextAuth
npm i next-auth
in NextAuth docs:
app/api/auth/[…nextauth]/route.js
import NextAuth from "next-auth/next";
import { options } from "./options";
const handler = NextAuth(options);
export { handler as GET, handler as POST };
app/api/auth/[…nextauth]/options.js
// basic structure see docs for more details and other options
export const options = {
providers: []
}
import GitHubProvider from "next-auth/providers/github";
import GoogleProvder from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
export const options = {
providers: [
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
GoogleProvder({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
placeholder: "[email protected]",
},
password: {
label: "Password",
type: "password",
placeholder: "********",
},
},
async authorize(credentials, req) {
// This is where you would add your own authentication logic
// to verify credentials from a database and return a user object if they are valid.
// Docs: <https://next-auth.js.org/configuration/providers/credentials>
const user = {
id: 1,
password: "password",
email: "[email protected]",
};
if (
credentials?.email === user.email &&
credentials?.password === user.password
) {
return user;
} else {
return null;
}
},
}),
],
};
Create .env.local in the root folder to store the client id and provider secrets
Generate the nextAuth secret in the terminal - openssl rand -base64 32
NEXTAUTH_SECRET=FzL53Yl0BKMy5inFJchNT7P2akuerfgerferwerf
GITHUB_SECRET=5bsdewvfervervevfedfvedw4
GITHUB_ID=Ov23ct9sjhdfvcb9X
GOOGLE_SECRET=5bsdewvfervervevfedfvedw4
GOOGLE_ID=Ov23ct9sjhdfvcb9X