Logo

dev-resources.site

for different kinds of informations.

Implementing auth.js v5 with Prisma and Supabase in Next.js

Published at
9/17/2024
Categories
authjs
nextjs
prisma
supabase
Author
heinhtoo
Categories
4 categories in total
authjs
open
nextjs
open
prisma
open
supabase
open
Author
8 person written this
heinhtoo
open
Implementing auth.js v5 with Prisma and Supabase in Next.js

With the new version auth.js v5 on the way, I am going to share my knowledge about step-by-step integrating it with Prisma and Supabase in Next.js.

Version

  • "next-auth": "^5.0.0-beta.20"
  • "@prisma/client": "^5.19.1"
  • "@auth/prisma-adapter": "^2.4.2"
  • "prisma": "^5.19.1"

Setting up Prisma

  • Install Prisma npm install prisma --save-dev
  • Initialize prisma npx prisma init
  • This will creates a new prisma directory with a schema.prisma file and configures PostgresSQL as your database also creating .env file with DATABASE_URL

Initialize Supabase

  1. Create organization in supabase (optional if you are individual developer)
  2. Create database
  3. Get connection string by clicking connect button.

Connect with supabase

  • Click ORMS and in Prisma, copy the .env.local into .env
    Env for Prisma

  • Click prisma/schema.prisma and copy the code inside your prisma.

Prisma Schema

Note. Prisma doesn't work on .env.local and it only works with .env so make sure to change the correct .env file

Setting NextAuth

  • Install auth.js v5
  • Adding NEXTAUTH_SECRET in env file npx auth secret
  • Add auth.ts file under src folder
// auth.ts
import NextAuth from 'next-auth';
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [],
})
Enter fullscreen mode Exit fullscreen mode
  • Add a route handler under app/api/auth/[...nextauth]/route.ts
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
Enter fullscreen mode Exit fullscreen mode
  • Add a middleware to keep session alive.
// middleware.ts
export { auth as middleware } from "@/auth"
Enter fullscreen mode Exit fullscreen mode
  • Add PrismaAdapter The Prisma Adapter in NextAuth.js is a tool that allows NextAuth to store and manage authentication data (such as user accounts, sessions, verification tokens, etc.) in a Prisma-managed database.

npm install @prisma/client @auth/prisma-adapter

To improve performance using Prisma ORM, we can set up the Prisma instance to ensure only one instance is created throughout the project and then import it from any file as needed. This approach avoids recreating instances of PrismaClient every time it is used.

// 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
Enter fullscreen mode Exit fullscreen mode
  • Add prisma Adapter in auth.ts
// auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/prisma"
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [],
})
Enter fullscreen mode Exit fullscreen mode
  • Define database tables for authentication by adding this in prisma/schema.prisma
// prisma/schema.prisma
model User {
  id            String          @id @default(cuid())
  firstName     String?
  lastName      String?
  email         String          @unique
  password      String? // Make sure this field exists in your schema
  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])
}
Enter fullscreen mode Exit fullscreen mode
  • Perform migration

In prisma, migrations need to perform except MongoDB.

A migration in the context of databases refers to the process of modifying the database schema in a controlled, versioned manner. This allows developers to make changes to the database structure (such as adding or removing tables, changing columns, or creating relationships) while keeping track of the changes. Migrations help ensure consistency across environments (like development, testing, and production) and make it easier to manage schema changes over time.

And in order to create SQL migration file,
npx prisma migrate dev

Note: Migration need to perform only when the schema changes

This will take a while if we are using Supabase URL and will prompt to ask migration name and after finished running this command, all the changes in schema will be updated in supabase and also creating migrations folder inside prisma/migrations

Note: In order to sync the migrations with supabase, donโ€™t delete migrations folder.

npx prisma migrate dev will also generate the Prisma client so the developer who is using this command may not need to run npx prisma generate.

But developers who pull from git will need to run npx prisma generate first to generate Prisma client.

Setting SessionProvider

We need to set session provider so that the client can use useSession hook.

Note: Need to add SessionProvider for all parent layout

// app/layout.tsx
import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { SessionProvider } from "next-auth/react";
import { auth } from "@/auth";

const geistSans = localFont({
  src: "./fonts/GeistVF.woff",
  variable: "--font-geist-sans",
  weight: "100 900",
});
const geistMono = localFont({
  src: "./fonts/GeistMonoVF.woff",
  variable: "--font-geist-mono",
  weight: "100 900",
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const session = await auth();

  return (
    <html lang="en">
      <body
        className={`${geistSans.variable} ${geistMono.variable} antialiased`}
      >
        <SessionProvider session={session}>{children}</SessionProvider>
      </body>
    </html>
  );
}

Enter fullscreen mode Exit fullscreen mode

Calling session from server pages or from api

import { auth } from '@/auth';
const session = await auth();
Enter fullscreen mode Exit fullscreen mode

Calling session from client components

"use client";
import { useSession } from 'next-auth/react';
const { data: session, status } = useSession();
Enter fullscreen mode Exit fullscreen mode

Conclusion

By combining the power of Prisma, Auth.js v5 and Supabase (as database), we can easily manage authentication in a Next.js app with minimal configuration but I haven't added any providers yet. This is the initial setup for now and will share about others providers later.

My GitHub Repo for next-auth Repo

Integrating LinkedIn Authentication Link

Integrating GitHub Authentication Link

Happy Coding ^_^

authjs Article's
30 articles in total
Favicon
Authentication System Using NodeJS
Favicon
Add Authjs to Next.js 15 app router with GitHub Authentication
Favicon
Master Authentication with Auth.js, Next.js, and PostgreSQL: A Comprehensive Guide
Favicon
Nuxt Authorization: How to Implement Team Role-Based Access Control in Nuxt 3
Favicon
Mastering Authentication in Next.js: A Step-by-Step Guide to GitHub Login with Auth.js
Favicon
User Authentication with Auth.js in Next.js App Router
Favicon
Lucia Auth is getting deprected
Favicon
Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide
Favicon
Simple Next.js Magic Link JWT Authentication with Prisma, PostgreSQL, and Resend
Favicon
Password Authentication with Auth.js in Astro and Customizing Session Information (auth-astro)
Favicon
Basic Authentication for Nuxt.js (JSON Web Token + Local Storage)
Favicon
Implementing Federated Sign-Out with Auth.js in Next.js 14 App Router
Favicon
Integrating LinkedIn Authentication with NextAuth.js: A Step-by-Step Guide
Favicon
Implementing auth.js v5 with Prisma and Supabase in Next.js
Favicon
Auth, OAuth, and Auth0: What is what?
Favicon
JWT Authentication and Cookie Management in Web Applications
Favicon
๐Ÿš€ Exciting News!
Favicon
Data Persistence (Cookies, Sessions, Tokens, LocalStorage and SessionStorage)
Favicon
Fashion website
Favicon
The Firebase Shortcut: Simplifying Next.js Authentication
Favicon
Authentication system in Next.Js using Auth.js
Favicon
Roles based authentication using Nextauth and next.js
Favicon
Authentication & Authorization
Favicon
Top User Authentication Tools for Developers
Favicon
Comprehensive Guide to SvelteKitAuth: Secure Authentication for SvelteKit Apps
Favicon
Building a Secure OTP-based Login System in Next.js
Favicon
Implementing Secure Authentication in Next.js with JWT and MongoDB. Protect Routes using middleware
Favicon
Next.js 14 and NextAuth v4 : Credentials Authentication A Detailed Step-by-Step Guide
Favicon
Building a Secure OTP-based Login System in Next.js
Favicon
Web3Auth(ๆฌกใฎjs)ใ‚’ไฝฟ็”จใ—ใŸXRP Ledgerใ‚ขใ‚ซใ‚ฆใƒณใƒˆใฎไฝœๆˆ:ใ‚นใƒ†ใƒƒใƒ—ใƒใ‚คใ‚นใƒ†ใƒƒใƒ—ใ‚ฌใ‚คใƒ‰

Featured ones: