When you want to add authentication to Next.js app, NextAuth.js is a good helper. This article shows the simple app with Next.js(App Router), NextAuth.js, Prisma, TypeScript, SQLite, GitHub OAuth.
This article libraries versions
Node.js 20.10.0
Next.js 14.0.4
NextAuth.js 5.0.0-beta.4
Next.js
Install Next.js
npx create-next-app@latest authjs-approuter-prisma-app
✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … Yes
✔ Would you like to use Tailwind CSS? … Yes
✔ Would you like to use `src/` directory? … Yes
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the default import alias (@/*)? … No
NextAuth.js
Install NextAuth.js
npm install next-auth@beta
Add auth.ts file
// auth.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import type { NextAuthConfig } from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const config = {
adapter: PrismaAdapter(prisma),
providers: [GitHub],
callbacks: {
authorized({ request, auth }) {
const { pathname } = request.nextUrl;
if (pathname === "/middleware-example") return !!auth;
return true;
},
},
} satisfies NextAuthConfig;
export const { handlers, auth, signIn, signOut } = NextAuth(config);
Add route.ts file
// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "../../../../../auth";
export const { GET, POST } = handlers;
Add Middleware settings
// middleware.ts
export { auth as middleware } from "./auth";
// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
Prisma
Install Prisma and initialize
npm install prisma --save-dev
npx prisma init --datasource-provider sqlite # MySQL or PostgreSQL instead of SQLite
NextAuth/Prisma
Install Prisma Adapter
npm install @prisma/client @auth/prisma-adapter
Add Prisma schema
// prisma/schema.prisma
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
Migrate Schema
npx prisma migrate dev
GitHub OAuth
This chapter shows how to set GitHub Key.
Go to this link
https://github.com/settings/applications/new
Register a new OAuth application
Generate a secret for AUTH_SECRET
openssl rand -base64 32
# Xh0Pvfu4VQsM+MEGw47Zo84eOZejKgjbL7XwdCyFQhM=
Set environment variables
# .env.local
AUTH_SECRET=Xh0Pvfu4VQsM+MEGw47Zo84eOZejKgjbL7XwdCyFQhM=
AUTH_GITHUB_ID=b9cb58b0c451fd68e1a2
AUTH_GITHUB_SECRET=2da087aed1d6ec3ec6509531c697d7d91eb0a112
Screen
Change appearance
// src/app/page.tsx
import { auth, signIn, signOut } from "../../auth";
export default async function Home() {
const session = await auth();
if (!session?.user)
return (
<div className="m-48">
<SignIn />
</div>
);
return (
<div className="m-48">
<p>{session.user.name}</p>
<p>{session.user.email}</p>
<SignOut />
</div>
);
}
export function SignIn() {
return (
<form
action={async () => {
"use server";
await signIn();
}}
>
<button>Sign In</button>
</form>
);
}
export function SignOut() {
return (
<form
action={async () => {
"use server";
await signOut();
}}
>
<button>Sign Out</button>
</form>
);
}
Let's run app
Let's check the app
npm run dev
npx prisma studio
Reference
https://github.com/nextauthjs/next-auth-example
https://next-auth.js.org/getting-started/example
https://next-auth.js.org/configuration/initialization#route-handlers-app
https://www.prisma.io/docs/getting-started/quickstart
https://authjs.dev/reference/adapter/prisma
Top comments (1)
This combination is love ❤️