Home > Web Front-end > JS Tutorial > User Authentication with Auth.js in Next.js App Router

User Authentication with Auth.js in Next.js App Router

Susan Sarandon
Release: 2024-11-12 03:05:01
Original
692 people have browsed it

Table of Contents

Initial Setup

  • Install
  • Configure
    • NextAuthConfig settings
    • Route Handler Setup
    • Middleware
    • Get Session in Server Side Component
    • Get Session in Client Side Component
  • Folder structure

Implementing Authentication: Credentials and Google OAuth

  • Setting up prisma
  • Credentials
  • Add Google OAuth Provider
    • Setting Google OAuth application
    • Setting Redirect URI
    • Setup Environment Variables
    • Setup Provider
  • Creating Login and Signup page
  • Folder Structure

Initial Setup

Install

npm install next-auth@beta
Copy after login
Copy after login
// env.local
AUTH_SECRET=GENERATETD_RANDOM_VALUE
Copy after login
Copy after login

Configure

NextAuthConfig settings

// src/auth.ts
import NextAuth from "next-auth"

export const config = {
  providers: [],
}

export const { handlers, signIn, signOut, auth } = NextAuth(config)
Copy after login
Copy after login

It should be put inside of src folder

Providers means in Auth.js are services that can be used to sign in a user. There are four ways a user can be signed in.

  • Using a built-in OAuth Provider(e.g Github, Google, etc...)
  • Using a custom OAuth Provider
  • Using Email
  • Using Credentials

https://authjs.dev/reference/nextjs#providers

Route Handler Setup

// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
Copy after login
Copy after login

This file is used for setting route handler with Next.js App Router.

Middleware

// src/middleware.ts
import { auth } from "@/auth"

export default auth((req) => {
  // Add your logic here
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], //  It's default setting
}
Copy after login
Copy after login

Write inside the src folder.
If written outside the src folder, middleware will not work.

Middleware is a function that allows you to run code before a request is completed. It is particularly useful for protecting routes and handling authentication across your application.

Matcher is a configuration option for specifying which routes middleware should apply to. It helps optimize performance by running middleware only on necessary routes.
Example matcher: ['/dashboard/:path*'] applies middleware only to dashboard routes.

https://authjs.dev/getting-started/session-management/protecting?framework=express#nextjs-middleware

Get Session in Server Side Component

// src/app/page.tsx
import { auth } from "@/auth"
import { redirect } from "next/navigation"

export default async function page() {
  const session = await auth()

  if (!session) {
    redirect('/login')
  }

  return (
    <div>
      <h1>Hello World!</h1>
      <img src={session.user.image} alt="User Avatar" />
    </div>
  )
}
Copy after login
Copy after login

Get Session in Client Side Component

// src/app/page.tsx
"use client"
import { useSession } from "next-auth/react"
import { useRouter } from "next/navigation"

export default async function page() {
  const { data: session } = useSession()
  const router = useRouter()

  if (!session.user) {
    router.push('/login')
  }

  return (
    <div>
      <h1>Hello World!</h1>
      <img src={session.user.image} alt="User Avatar" />
    </div>
  )
}

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

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

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  );
}
Copy after login
Copy after login

Folder structure

/src
  /app
    /api
      /auth
        [...nextauth]
          /route.ts  // Route Handler
    layout.tsx
    page.tsx

  auth.ts  // Provider, Callback, Logic etc
  middleware.ts  // A function before request
Copy after login
Copy after login

Implementing Authentication: Credentials and Google OAuth

Setting up prisma

// prisma/schema.prisma

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  password      String?
  accounts      Account[]
  sessions      Session[]
}

model Account {
  // ... (standard Auth.js Account model)
}

model Session {
  // ... (standard Auth.js Session model)
}

// ... (other necessary models)

Copy after login
Copy after login
// src/lib/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
Copy after login

Credentials

Credentials, in the context of authentication, refer to a method of verifying a user's identity using information that the user provides, typically a username (or email) and password.

We can add credentials in src/auth.ts.

npm install next-auth@beta
Copy after login
Copy after login

adapters:

  • modules that connect your authentication system to your database or data storage solution.

secret:

  • This is a random string used to hash tokens, sign/encrypt cookies, and generate cryptographic keys.
  • It's crucial for security and should be kept secret.
  • In this case, it's set using an environment variable AUTH_SECRET.

pages:

  • This object allows you to customize the URLs for authentication pages.
  • In your example, signIn: '/login' means the sign-in page will be at the '/login' route instead of the default '/api/auth/signin'.

session:

  • This configures how sessions are handled.
  • strategy: "jwt" means JSON Web Tokens will be used for session management instead of database sessions.

callbacks:

  • These are functions that are called at various points in the authentication flow, allowing you to customize the process.

jwt callback:

  • This runs when a JWT is created or updated.
  • In your code, it's adding user information (id, email, name) to the token.

session callback:

  • This runs whenever a session is checked.
  • Your code is adding the user information from the token to the session object.

Add Google OAuth Provider

Setting Google OAuth application

Create new OAuth Client ID from GCP Console > APIs & Services > Credentials

User Authentication with Auth.js in Next.js App Router

Once created, save your Client ID and Client Secret for later use.

Setting Redirect URI

When we work in local, set http://localhost:3000/api/auth/callback/google

In production environment, just replace http://localhost:3000 with https://------.

User Authentication with Auth.js in Next.js App Router

Setup Environment Variables

// env.local
AUTH_SECRET=GENERATETD_RANDOM_VALUE
Copy after login
Copy after login

Setup Provider

// src/auth.ts
import NextAuth from "next-auth"

export const config = {
  providers: [],
}

export const { handlers, signIn, signOut, auth } = NextAuth(config)
Copy after login
Copy after login

https://authjs.dev/getting-started/authentication/oauth

Creating Login and Signup page

// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
Copy after login
Copy after login
// src/middleware.ts
import { auth } from "@/auth"

export default auth((req) => {
  // Add your logic here
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], //  It's default setting
}
Copy after login
Copy after login
// src/app/page.tsx
import { auth } from "@/auth"
import { redirect } from "next/navigation"

export default async function page() {
  const session = await auth()

  if (!session) {
    redirect('/login')
  }

  return (
    <div>
      <h1>Hello World!</h1>
      <img src={session.user.image} alt="User Avatar" />
    </div>
  )
}
Copy after login
Copy after login
// src/app/page.tsx
"use client"
import { useSession } from "next-auth/react"
import { useRouter } from "next/navigation"

export default async function page() {
  const { data: session } = useSession()
  const router = useRouter()

  if (!session.user) {
    router.push('/login')
  }

  return (
    <div>
      <h1>Hello World!</h1>
      <img src={session.user.image} alt="User Avatar" />
    </div>
  )
}

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

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

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  );
}
Copy after login
Copy after login
/src
  /app
    /api
      /auth
        [...nextauth]
          /route.ts  // Route Handler
    layout.tsx
    page.tsx

  auth.ts  // Provider, Callback, Logic etc
  middleware.ts  // A function before request
Copy after login
Copy after login

Folder Structure

// prisma/schema.prisma

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  password      String?
  accounts      Account[]
  sessions      Session[]
}

model Account {
  // ... (standard Auth.js Account model)
}

model Session {
  // ... (standard Auth.js Session model)
}

// ... (other necessary models)

Copy after login
Copy after login

The above is the detailed content of User Authentication with Auth.js in Next.js App Router. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template