0
0
NextJSframework~5 mins

Provider configuration (OAuth, credentials) in NextJS

Choose your learning style9 modes available
Introduction

Provider configuration lets your Next.js app connect with services like Google or GitHub for login. It makes signing in easy and safe.

You want users to log in using their Google or Facebook accounts.
You need to allow users to sign in with a username and password stored securely.
You want to add social login options to your app quickly.
You want to manage user authentication without building it from scratch.
Syntax
NextJS
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ]
});

Use environment variables to keep your client ID and secret safe.

Each provider needs its own client ID and secret from its developer console.

Examples
This example shows how to set up a simple username and password login using credentials.
NextJS
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (credentials.username === "user" && credentials.password === "pass") {
          return { id: 1, name: "User" };
        }
        return null;
      }
    })
  ]
});
This example configures GitHub as an OAuth provider for login.
NextJS
import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET
    })
  ]
});
Sample Program

This is a complete NextAuth configuration using Google OAuth. It uses environment variables for sensitive info. When users visit the sign-in page, they can choose Google to log in.

NextJS
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ],
  secret: process.env.NEXTAUTH_SECRET
});
OutputSuccess
Important Notes

Always keep your client secrets in environment variables, never in code.

OAuth providers require you to register your app and get client IDs and secrets.

Credentials provider needs you to write your own user check logic inside authorize.

Summary

Provider configuration connects your app to login services like Google or GitHub.

Use environment variables to keep secrets safe.

Choose OAuth providers for social login or credentials for username/password.