1. Home
  2. 6 Steps Streamlined Guide to Configuring Next.js 15 with NextAuth v5, PostgreSQL, and Prisma Social login using GitHub and Google

6 Steps Streamlined Guide to Configuring Next.js 15 with NextAuth v5, PostgreSQL, and Prisma Social login using GitHub and Google

Reading TIme:6 min
Published on:January 2, 2025
nextjsnext-authauthjsprismapostgresqldeveloper toolsSingin with OAuth2

Next.js and NextAuth configuration guide header image

Introduction

Configuring a modern web application with tools like Next.js 15, Next-Auth v5/Authjs, PostgreSQL, and Prisma Social login using GitHub and Google OAuth can be daunting. Developers often encounter challenges such as mismatched dependencies, improper database setup, or incomplete integration between authentication and data persistence layers. These hurdles can consume significant time, disrupt workflows, and lead to frustration, especially for teams on tight deadlines.

This guide is here to help. By following these six simple steps, your team can:

  • Efficiently set up a fully functional web application with authentication.
  • Avoid common configuration mistakes.
  • Streamline the integration process, saving several days of trial and error.

To make the process even smoother, we've created a GitHub repository containing the entire configuration process for your reference.

By the end of this guide, you will have a working example of Next.js with authentication powered by GitHub and Google, a PostgreSQL database managed by Prisma, and a scalable, developer-friendly setup. Let’s get started.


Prerequisite

Before diving into the configuration steps, ensure you have the following installed on your system:

  1. Node.js: Download and install the latest LTS version from Node.js official website.

    Terminal
    node -v
     
    run this in terminal or command-prompt

    Use this command to verify installation.

  2. PostgreSQL: or similar tools Download and install PostgreSQL from PostgreSQL official website.

    Terminal
    psql --version
     
    run this in terminal or command-prompt

    Verify the installation with the above command.


Step-by-Step Guide

1. Create a New Next.js Project

Why: Starting with a clean slate ensures compatibility with the latest features and avoids issues from legacy configurations.

Command:

Terminal
npx create-next-app@latest nextjs-15-next-auth-v5-github-google-prisma-postgres-template
cd nextjs-15-next-auth-v5-github-google-prisma-postgres-template
 
run this in terminal or command-prompt

This command scaffolds a new Next.js project in a directory named nextjs-15-next-auth-v5-github-google-prisma-postgres-template.


2. Install Required Dependencies

Why: Dependencies provide the necessary libraries and tools for authentication, database interaction, and Prisma ORM setup.

Command:

Terminal
npm install -S next-auth@beta @prisma/client @auth/prisma-adapter
npm install -D prisma
 
run this in terminal or command-prompt

These commands install:

  • NextAuth v5 (Beta): For authentication.
  • Prisma Client: For database ORM.
  • Prisma Adapter: To connect NextAuth to Prisma.
  • Prisma CLI (Dev Dependency): For database schema management.

3. Database Setup

Why: A robust database is essential for storing user data and application content.

  1. Create a PostgreSQL Database Open the PostgreSQL CLI an run below command:

    Create Database
    CREATE DATABASE mydb;
     
     
     
    run above command in psql cli or use your preferred tool to create a postgres database

    Replace mydb with your preferred database name.

  2. Update Environment Variables In the .env file, add the connection string:

    .env
    DATABASE_URL=<update it according to your database connection string.>
    DIRECT_URL=<update it according to your database connection string.>
     
     
     
     
     
     
     
    values from .env.* file will not read by prisma, prisma init command mentioned below will automatically generate sample string in .env file for you.

    Ensure the username, password, and database name match your PostgreSQL setup.


4. Prisma Setup

Why: Prisma simplifies database interactions and provides a schema-driven approach to manage tables and models.

  1. Initialize Prisma:

    Terminal
    npx prisma init
     
    run this in terminal or command-prompt

    This command creates a prisma directory with a default schema.prisma file.

  2. Add NextAuth Models: Update schema.prisma to include NextAuth models. Refer to the NextAuth Prisma Adapter documentation for exact models.

    prisma/schema.prisma
    // This is your Prisma schema file,
    // learn more about it in the docs: https://pris.ly/d/prisma-schema
     
    // Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
    // Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
     
    generator client {
       provider = "prisma-client-js"
    }
     
    datasource db {
       provider  = "postgresql"
       url       = env("DATABASE_URL")
       directUrl = env("DIRECT_URL")
    }
     
    model Account {
       id                String  @id @default(cuid())
       userId            String  @map("user_id")
       type              String
       provider          String
       providerAccountId String  @map("provider_account_id")
       refresh_token     String? @db.Text
       access_token      String? @db.Text
       expires_at        Int?
       token_type        String?
       scope             String?
       id_token          String? @db.Text
       session_state     String?
     
       user User @relation(fields: [userId], references: [id], onDelete: Cascade)
     
       @@unique([provider, providerAccountId])
       @@map("accounts")
    }
     
    model Session {
       id           String   @id @default(cuid())
       sessionToken String   @unique @map("session_token")
       userId       String   @map("user_id")
       expires      DateTime
       user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
     
       @@map("sessions")
    }
     
    model User {
       id            String    @id @default(cuid())
       name          String?
       email         String?   @unique
       emailVerified DateTime? @map("email_verified")
       image         String?
       accounts      Account[]
       sessions      Session[]
     
       @@map("users")
    }
     
    model VerificationToken {
       identifier String
       token      String
       expires    DateTime
     
       @@unique([identifier, token])
       @@map("verification_tokens")
    }
     
     
     
     
    prisma init will generate sample file and you can update the remaining file accordingly.
  3. Generate Prisma Client:(Optional)

    Terminal
    npx prisma generate
     
    run this in terminal or command-prompt
  4. Create a Prisma Helper File: In the lib directory, create prisma.ts:

    Terminal
    import { PrismaClient } from "@prisma/client";
    const prisma = new PrismaClient();
    export default prisma;
  5. Update package.json: Add a post-install script:

    package.json
    // "postinstall": "prisma generate && prisma migrate dev --name init_with_next_auth"
    {
       ...
       "scripts": {
          ...
          "postinstall": "prisma generate && prisma migrate dev --name init_with_next_auth"
       },
       ...
    }
     
    add this in the scripts block
  6. Run the Post-Install Script:

    Terminal
    npm install
     
    run this in terminal or command-prompt

    This creates tables in your database.


5. NextAuth Setup

Why: NextAuth provides authentication with multiple providers, such as GitHub and Google.

  1. Generate a Secret:

    Terminal
    npx auth secret
     
    run this in terminal or command-prompt

    Add the generated secret to your .env file:

    .env.local
    AUTH_SECRET=your_generated_secret
     
     
     
     
     
    Ideally, this will be auto added by above command please verify it and add if it's don't exist.s
  2. Set Up OAuth Applications:

    • Create applications in GitHub and Google Developer Consoles. You can follow Next-Auth GitHub Integration and Next-Auth Google Integration simple guide for creation of Google/Github OAuth apps.
    • Add client IDs and secrets to your .env file:
      .env.local
      AUTH_GITHUB_ID=your_github_id
      AUTH_GITHUB_SECRET=your_github_secret
      AUTH_GOOGLE_ID=your_google_id
      AUTH_GOOGLE_SECRET=your_google_secret
       
       
       
       
       
      You'll get these values from GitHub/Google or similar OAuth providers
  3. Configure NextAuth: Create auth.ts in the /app/api/auth/[...nextauth] directory:

    auth.ts
    import NextAuth from "next-auth";
    import { PrismaAdapter } from "@auth/prisma-adapter";
    import Google from "next-auth/providers/google";
    import GitHub from "next-auth/providers/github";
     
    import { prisma } from "@/lib/prisma";
     
    export const { handlers, auth, signIn, signOut } = NextAuth({
      adapter: PrismaAdapter(prisma),
      providers: [GitHub, Google],
      session: { strategy: "jwt" },
      callbacks: {
        authorized: async ({ auth }) => {
          // Logged in users are authenticated, otherwise redirect to login page
          return !!auth;
        },
      },
    });

6. Protect Your Routes

Why: Middleware ensures that only authenticated users access protected pages.

  1. Create a middleware.ts File:

    Terminal
    export { auth as middleware } from "@/auth";
     
    // Protecting Articles APIs route. Add more routes here in the future to protect them behind authentication.
    export const config = {
      /**
       * `Most important NOTE`
       *
       * below matcher should not contain `/api/auth` path.
       * Otherwise it'll introduce an infinite retries b/w your Identity provider
       * and your application issue and you won't be able login successfully.
       *
       * 1. Below matcher automatically protect all the APIs writen inside /app/api/blogs folder.
       * 2. You can add more paths here based on your requirement but
       *    keep above `important NOTE` in mind while adding paths.
       */
      matcher: ["/api/blogs/:path*"],
    };
     
     
     
    above matcher should not contain /api/auth path directly or indirectly.

    This middleware redirects unauthenticated users to the sign-in page.


Tha's it. Our configuration for Next.js 15, Next-Auth v5/Authjs, GitHub, Google OAuth, PostgreSQL, and Prisma is done successfully and it's testing time.

Testing Your Configuration

Why: Testing ensures that all components are correctly set up and working together seamlessly.

  1. Verify Database Migration:

    • Open your PostgreSQL database and check the users, accounts, sessions, and verification_tokens tables got created during prisma migrate schema migration stage to ensure user data can be saved correctly.
  2. Run Your Application: Start the development server:

    terminal
    npm run dev
     
     
     
     
     
    you can also run npm build followed by npm start to ensure application is working after building...
  3. Check Authentication:

    • Navigate to /api/auth/signin or /api/blogs/:path* to test the login functionality.
    • Try logging in using GitHub or Google credentials.
  4. Verify Database Integration:

    • Open your PostgreSQL database and check the users, and accounts tables to ensure user data is being saved correctly.
  5. Test Protected Routes:

    • Access a protected page like /api/blogs/:path* in this case which got added into the middleware.ts file.
    • Ensure unauthenticated users are redirected to the sign-in page and being redirected back correctly upon successful login at the same time already authenticated users can access the content directly without being promted for signin again.

Conclusion

By following this guide, you’ve successfully configured Next.js 15, Next-Auth v5/Authjs, PostgreSQL, and Prisma Social login using GitHub and Google in just six steps. This comprehensive setup, often requiring several days of effort, is now streamlined to save your team valuable time and effort. With authentication, database, and API routes fully integrated, you now have a robust and scalable application ready for production.

For your convenience, we’ve also created a nextjs-15-next-auth-v5-github-google-prisma-postgres-template GitHub repository containing the entire configuration process.


Additional References

Happy Coding!

nextjsnext-authauthjsprismapostgresqldeveloper toolsSingin with OAuth2
More like this