2024-10-23
First, create a compose.yaml
file to define your PostgreSQL service:
version: '3.8'
services:
database:
image: postgres:latest
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: password
POSTGRES_DB: pgdb
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
volumes:
postgres_data:
To start the database:
docker-compose up
(for Docker users).podman-compose up
(for Fedora/Podman users . if you have feodra it works like a charm , try podman[podman.io] out ! ).Your database URL will look like this:
postgresql://admin:password@localhost:5432/pgdb
This is the DB URL : postgresql://<user>:<password>@localhost:<port>/<dbname>
http://localhost:3000
http://localhost:3000/api/auth/callback/google
Copy the Client ID and Client Secret.
Create a .env.local
file in your project root and add the following:
GOOGLE_CLIENT_ID="Paste your Google client ID here"
GOOGLE_CLIENT_SECRET="Paste your Google client secret here"
http://localhost:3000/api/auth/callback/discord
Copy the Client ID and Client Secret.
Add the following to your .env.local
file:
DISCORD_CLIENT_ID="Paste your Discord client ID here"
DISCORD_CLIENT_SECRET="Paste your Discord client secret here"
Visit GitHub Developer Settings and create a new OAuth application.
Fill out the following details:
http://localhost:3000
http://localhost:3000/api/auth/callback/github
Copy the Client ID and Client Secret.
Add the following to your .env.local
file:
GITHUB_CLIENT_ID="Paste your GitHub client ID here"
GITHUB_CLIENT_SECRET="Paste your GitHub client secret here"
.env.local
File Example:GOOGLE_CLIENT_ID="Paste your Google client ID here"
GOOGLE_CLIENT_SECRET="Paste your Google client secret here"
DISCORD_CLIENT_ID="Paste your Discord client ID here"
DISCORD_CLIENT_SECRET="Paste your Discord client secret here"
GITHUB_CLIENT_ID="Paste your GitHub client ID here"
GITHUB_CLIENT_SECRET="Paste your GitHub client secret here"
DATABASE_URL="postgresql://admin:password@localhost:5432/pgdb"
Install the necessary dependencies:
npm install next-auth
To configure Prisma with your NextAuth setup, follow the steps below:
Run the following commands to install Prisma and its client, along with the NextAuth Prisma adapter:
npm install @prisma/client @auth/prisma-adapter
npm install prisma --save-dev
Run the following command to initialize Prisma in your project:
npx prisma init
This will create a prisma
folder with a schema.prisma
file and a .env
file.
In the prisma/schema.prisma
file, modify it to define the User
, Account
, Session
, and VerificationToken
models as needed by NextAuth:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(cuid())
name String?
email String @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
// Optional for WebAuthn support
Authenticator Authenticator[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Account {
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?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([provider, providerAccountId])
}
model Session {
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model VerificationToken {
identifier String
token String
expires DateTime
@@id([identifier, token])
}
// Optional for WebAuthn support
model Authenticator {
credentialID String @unique
userId String
providerAccountId String
credentialPublicKey String
counter Int
credentialDeviceType String
credentialBackedUp Boolean
transports String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([userId, credentialID])
}
Once the schema is set, you'll need to create and apply a migration to your database:
npx prisma migrate dev --name init
This will generate the necessary tables in your database based on the schema defined above.
Now, you'll set up Prisma to avoid creating multiple instances across your project:
prisma.ts
file:In your project, create a prisma.ts
file to instantiate Prisma:
// prisma.ts
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
export const prisma = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
In your auth.ts
or route.ts
file for NextAuth (using the Next.js 13.2 Route Handlers), initialize NextAuth with the Prisma adapter:
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/prisma";
const handler = NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
authorization: {params: {scope: scopes.join(' ')}},
}),
GithubProvider({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
})
],
});
export { handler as GET, handler as POST };
.env
file:Ensure that your .env
file has the correct database connection string:
DATABASE_URL="postgresql://admin:password@localhost:5432/pgdb"
After setting everything up, run your Next.js app:
npm run dev
Now your app is configured to use NextAuth with Google, Discord, GitHub OAuth, and Prisma ORM with PostgreSQL.