Back to Community Uploads

Authentication Flow with NextAuth.js

A complete authentication system with social logins, email verification, and role-based access control

Project Information

Author

Michael Chen

Technology

Next.js, NextAuth.js

Last Updated

June 3, 2023

Authentication Features

Social login with Google, GitHub, and more
Email and password authentication
Email verification flow
Role-based access control
Password reset functionality
JWT and session-based authentication
Protected routes and middleware
User profile management

Implementation Example

// auth.ts
import NextAuth from 'next-auth';
import { NextAuthConfig } from 'next-auth';
import Google from 'next-auth/providers/google';
import GitHub from 'next-auth/providers/github';
import Credentials from 'next-auth/providers/credentials';
import { z } from 'zod';
import { compare } from 'bcrypt';
import { getUserByEmail } from '@/lib/user';

export const authConfig: NextAuthConfig = {
providers: [
Google({
  clientId: process.env.YOUR_GOOGLE_CLIENT_ID,
  clientSecret: process.env.YOUR_GOOGLE_CLIENT_SECRET,
}),
GitHub({
  clientId: process.env.YOUR_GITHUB_CLIENT_ID,
  clientSecret: process.env.YOUR_GITHUB_CLIENT_SECRET,
}),
Credentials({
  credentials: {
    email: { label: 'Email', type: 'email' },
    password: { label: 'Password', type: 'password' }
  },
  async authorize(credentials) {
    const parsedCredentials = z
      .object({ email: z.string().email(), password: z.string().min(6) })
      .safeParse(credentials);

    if (parsedCredentials.success) {
      const { email, password } = parsedCredentials.data;
      const user = await getUserByEmail(email);
      if (!user) return null;
      
      const passwordsMatch = await compare(password, user.password);
      if (passwordsMatch) return user;
    }
    
    return null;
  },
}),
],
pages: {
signIn: '/auth/login',
error: '/auth/error',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
  const isLoggedIn = !!auth?.user;
  const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
  if (isOnDashboard) {
    if (isLoggedIn) return true;
    return false; // Redirect unauthenticated users to login page
  } else if (isLoggedIn) {
    return true;
  }
  return true;
},
jwt({ token, user }) {
  if (user) {
    token.role = user.role;
    token.id = user.id;
  }
  return token;
},
session({ session, token }) {
  if (token && session.user) {
    session.user.role = token.role;
    session.user.id = token.id;
  }
  return session;
},
},
};

export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);

Usage Instructions

  1. Clone the repository to your local machine using git clone https://github.com/username/nextauth-flow.git
  2. Install dependencies with npm install or yarn install
  3. Set up your environment variables in .env.local:
    • NEXTAUTH_URL - Your site URL
    • YOUR_NEXTAUTH_SECRET - A random string for JWT encryption
    • YOUR_GOOGLE_CLIENT_ID and YOUR_GOOGLE_CLIENT_SECRET - From Google Developer Console
    • YOUR_GITHUB_CLIENT_ID and YOUR_GITHUB_CLIENT_SECRET - From GitHub Developer Settings
  4. Run the development server with npm run dev or yarn dev
  5. Customize the authentication UI components in the app/auth directory
  6. Implement your protected routes using the auth() middleware

Ready to Implement Secure Authentication?

Download the complete authentication flow and add secure user authentication to your Next.js application.

View on GitHub Live Demo