Implementing Authentication in Next.js – Secure Sign-Up, Validation, and Session Management

Authentication in Next.js involves verifying user identity, managing sessions, and controlling access to routes. This article walks through building a secure sign-up form using Server Actions and useActionState, validating fields with Zod, and creating user accounts with hashed passwords. It also highlights best practices and tips for improving user experience.

Next.js authenticationServer ActionsuseActionStateZod validationSession management

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۴ آبان ۱۴۰۴

Understanding Authentication in Next.js


Authentication ensures users are who they claim to be. It includes:

  • Authentication: Verifying identity (e.g. username and password)
  • Session Management: Tracking auth state across requests
  • Authorization: Controlling access to routes and data

Step 1 – Capture User Credentials


Create a form that submits to a Server Action:

// app/ui/signup-form.tsx
import { signup } from '@/app/actions/auth'

export function SignupForm() {
  return (
    <form action={signup}>
      <input name="name" placeholder="Name" />
      <input name="email" type="email" placeholder="Email" />
      <input name="password" type="password" />
      <button type="submit">Sign Up</button>
    </form>
  )
}

Step 2 – Validate Fields on the Server


Use Zod to define a schema:

// app/lib/definitions.ts
import * as z from 'zod'

export const SignupFormSchema = z.object({
  name: z.string().min(2).trim(),
  email: z.email().trim(),
  password: z
    .string()
    .min(8)
    .regex(/[a-zA-Z]/)
    .regex(/[0-9]/)
    .regex(/[^a-zA-Z0-9]/)
    .trim(),
})

Validate and return errors early:

// app/actions/auth.ts
import { SignupFormSchema } from '@/app/lib/definitions'

export async function signup(_, formData) {
  const validated = SignupFormSchema.safeParse({
    name: formData.get('name'),
    email: formData.get('email'),
    password: formData.get('password'),
  })

  if (!validated.success) {
    return {
      errors: validated.error.flatten().fieldErrors,
    }
  }

  // Proceed to create user...
}

Step 3 – Display Validation Errors


Use useActionState to show errors in the form:

// app/ui/signup-form.tsx
'use client'
import { signup } from '@/app/actions/auth'
import { useActionState } from 'react'

export default function SignupForm() {
  const [state, action, pending] = useActionState(signup, undefined)

  return (
    <form action={action}>
      <input name="name" />
      {state?.errors?.name && <p>{state.errors.name}</p>}

      <input name="email" />
      {state?.errors?.email && <p>{state.errors.email}</p>}

      <input name="password" type="password" />
      {state?.errors?.password && (
        <ul>
          {state.errors.password.map((e) => <li key={e}>{e}</li>)}
        </ul>
      )}

      <button disabled={pending}>Sign Up</button>
    </form>
  )
}

Step 4 – Create User Account


Hash the password and insert the user into your database:

// app/actions/auth.ts
import bcrypt from 'bcrypt'

export async function signup(_, formData) {
  // Validate...
  const { name, email, password } = validated.data
  const hashedPassword = await bcrypt.hash(password, 10)

  const user = await db.insert(users).values({
    name,
    email,
    password: hashedPassword,
  }).returning({ id: users.id })

  if (!user) {
    return { message: 'Error creating account.' }
  }

  // TODO: Create session and redirect
}

Tips and Best Practices


  • Use an authentication library for simplicity and security
  • Check for duplicate emails/usernames early in the form flow
  • Use debounce libraries to reduce validation request frequency
  • Always authorize users before mutating data

Conclusion


Authentication in Next.js is secure and scalable with Server Actions, form validation, and session management. While custom solutions are possible, using a trusted Auth Library can simplify the process and enhance security.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه