Authentication

Authentication in Next.js with NextAuth.js (Auth.js)

S

Sajan Acharya

Author

October 25, 2024
15 min read

Introduction

NextAuth.js is the standard authentication solution for Next.js applications. It supports OAuth providers (Google, GitHub, etc.), email magic links, and custom credentials.

Installation

First, install NextAuth.js in your Next.js project:

# Using npm
    npm install next-auth

    # Using yarn
    yarn add next-auth
    

Install OAuth providers you want to use (example: GitHub):

npm install next-auth @next-auth/github-provider
    

Setup

Create a catch-all API route at app/api/auth/[...nextauth]/route.ts:

import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"

const handler = NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
})

export { handler as GET, handler as POST }

Environment Variables

Set up your .env.local file:

GITHUB_ID=your_github_client_id
GITHUB_SECRET=your_github_client_secret
NEXTAUTH_SECRET=a_long_random_secret_string
NEXTAUTH_URL=http://localhost:3000
    

Protecting Routes

Use middleware.ts to secure pages, like your dashboard:

import { withAuth } from "next-auth/middleware"

export default withAuth({
  pages: {
    signIn: "/login", // Redirect unauthenticated users here
  },
})

export const config = { matcher: ["/dashboard/:path*"] }

Client Usage

Access session info and authentication functions in your components:

import { useSession, signIn, signOut } from "next-auth/react"

export default function Dashboard() {
  const { data: session } = useSession()

  if (!session) {
    return (
      

You must be signed in to view this page.

) } return (

Welcome, {session.user?.name}!

) }

Terminal Commands for Running & Testing

  • Run your Next.js app in development mode: npm run dev or yarn dev
  • Build your app for production: npm run build or yarn build
  • Start the production server: npm start or yarn start
  • Check your environment variables: echo $GITHUB_ID (Mac/Linux) or echo %GITHUB_ID% (Windows)

Tips & Best Practices

  • Always keep NEXTAUTH_SECRET safe and random for signing tokens.
  • Use HTTPS in production for secure cookies.
  • Combine multiple providers (Google, GitHub, Credentials) to give users more login options.
  • Test authentication in a local environment before deploying.

Conclusion

NextAuth.js simplifies authentication in Next.js apps with minimal setup. By combining OAuth providers, credentials, and middleware protection, you can secure your entire application effectively. This setup ensures a smooth developer experience and robust security for your users.

Tags

#Next.js#Authentication#Security#NextAuth.js#OAuth

Share this article

About the Author

S

Sajan Acharya

Content Writer

Passionate about technology and sharing knowledge with the community.

Stay Updated

Get the latest articles delivered to your inbox