Next.js Authentication
Next.js authentication is about proving who a user is, then remembering that fact across requests. In the App Router, you handle this on the server with cookies and Server Actions, so the browser never sees your secrets. Getting it right matters because a single mistake can expose private data or let anyone pretend to be someone else.
This tutorial builds a minimal login system step by step. You will create a Server Action that checks credentials, signs a session cookie with the jose library, and redirects the user. You will also write a getSession helper, protect a /dashboard page, and add a logout action. Along the way, you will learn why proxy.ts is only for optimistic redirects, not real security.
If you have not used Server Actions before, read Next.js Forms & Server Actions first. The session-cookie pattern here also connects to Next.js Middleware, which is now called proxy.ts in Next.js 16.
Security note: The code in this tutorial is for learning. It uses a hardcoded demo user and a simple session cookie. For production, use a vetted authentication library and a real database with hashed passwords. Never copy this code into a live application without adding proper security measures.
What Is Next.js Authentication and Why Does It Matter?
Next.js authentication is the process of verifying a user's identity, usually with an email and password, and storing that verified state in a session. Authentication answers "who are you?" while authorization answers "what are you allowed to do?" Both must happen on the server .
Here is the smallest mental model. A user submits a login form. The server checks the password. If it matches, the server creates a signed token and puts it in an HttpOnly cookie. On every later request, the server reads that cookie to know who the user is.
// Conceptual flow, not runnable code
// 1. User submits email and password
// 2. Server verifies credentials
// 3. Server creates a signed session token
// 4. Server sets it as an HttpOnly cookie
// 5. Later requests send the cookie automatically
// 6. Server reads and verifies the cookie
How it works: The cookie is the key. Because it is HttpOnly, JavaScript in the browser cannot read it. Because it is signed, the server can detect if someone tampered with it. This is the foundation of session-based authentication, and it works well with Next.js because Server Components and Server Actions can read and write cookies on the server .
Authentication vs Authorization in Plain Language
These two words sound similar but mean different things. Authentication is checking that the user is who they claim to be. Authorization is checking whether that user is allowed to do or see something.
| Question | Concept | Example |
|---|---|---|
| Who is this user? | Authentication | Checking email and password at login |
| Can this user view the admin page? | Authorization | Checking if user.role === "admin" |
| Can this user delete this post? | Authorization | Checking if the post belongs to the user |
How it works: A user can be authenticated but not authorized. For example, a logged-in customer is authenticated, but they are not authorized to open the admin dashboard. Always check both. Authentication tells you there is a valid session. Authorization tells you what that session can do .
How Session Cookies Work: HttpOnly, Secure, SameSite
A session cookie is a small piece of data stored by the browser and sent with every request to your server. Three flags make it safer: HttpOnly, Secure, and SameSite.
HttpOnly: JavaScript cannot read the cookie. This protects against cross-site scripting (XSS) attacks that try to steal the token.Secure: The cookie is only sent over HTTPS. This prevents it from being intercepted on an insecure connection.SameSite=lax: The cookie is not sent on most cross-site requests. This reduces the risk of cross-site request forgery (CSRF) attacks.
// app/actions/auth.ts (partial example)
import { cookies } from "next/headers";
export async function demo() {
const cookieStore = await cookies();
cookieStore.set("session", "token-value", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
}
How it works: In Next.js 16, cookies() is an async function. You must await it before calling .set() or .get() . The set method only works in a Server Action or Route Handler, because setting a cookie requires sending a response header, and Server Components cannot modify the response. The maxAge value is in seconds, so 60 * 60 * 24 * 7 is one week.
Building a Login Flow with a Server Action
A login flow takes credentials, verifies them, creates a session, and redirects the user. In the App Router, this fits naturally into a Server Action connected to a form.
Installing jose
# Terminal
npm install jose
Output: The jose package is added to your dependencies. It provides SignJWT and jwtVerify for creating and checking signed tokens.
The session helper
// lib/session.ts
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
const secretKey = new TextEncoder().encode(
process.env.SESSION_SECRET ?? "dev-only-secret-change-me"
);
export type SessionPayload = {
userId: string;
email: string;
};
export async function createSession(payload: SessionPayload) {
const token = await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("7d")
.sign(secretKey);
const cookieStore = await cookies();
cookieStore.set("session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
}
export async function getSession(): Promise<SessionPayload | null> {
const cookieStore = await cookies();
const token = cookieStore.get("session")?.value;
if (!token) return null;
try {
const { payload } = await jwtVerify(token, secretKey);
return {
userId: String(payload.userId),
email: String(payload.email),
};
} catch {
return null;
}
}
export async function deleteSession() {
const cookieStore = await cookies();
cookieStore.delete("session");
}
export async function requireSession(): Promise<SessionPayload> {
const session = await getSession();
if (!session) {
redirect("/login");
}
return session;
}
How it works: createSession signs a JWT with the user's ID and email, then stores it in an HttpOnly cookie. getSession reads the cookie, verifies the signature, and returns the payload or null. requireSession is a convenience wrapper that redirects to /login if there is no valid session. The SESSION_SECRET environment variable should be a long random string in production. The fallback value is only for local development .
The login Server Action and page
// app/actions/auth.ts
"use server";
import { createSession } from "@/lib/session";
// Demo user only. Never hardcode passwords in production.
const DEMO_USER = {
id: "1",
email: "student@example.com",
password: "password123",
};
export type LoginState = {
error: string | null;
};
export async function login(
_prevState: LoginState,
formData: FormData
): Promise<LoginState> {
const email = formData.get("email");
const password = formData.get("password");
if (typeof email !== "string" || typeof password !== "string") {
return { error: "Email and password are required" };
}
if (email !== DEMO_USER.email || password !== DEMO_USER.password) {
return { error: "Invalid email or password" };
}
await createSession({ userId: DEMO_USER.id, email: DEMO_USER.email });
return { error: null };
}
// app/login/page.tsx
"use client";
import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { login, type LoginState } from "../actions/auth";
const initialState: LoginState = { error: null };
export default function LoginPage() {
const [state, formAction] = useActionState(login, initialState);
const router = useRouter();
useEffect(() => {
if (state.error === null) {
router.push("/dashboard");
}
}, [state, router]);
return (
<form action={formAction}>
<input name="email" type="email" placeholder="Email" />
<input name="password" type="password" placeholder="Password" />
{state.error && <p>{state.error}</p>}
<button type="submit">Log in</button>
</form>
);
}
Browser shows: Submitting the demo credentials redirects to /dashboard. Submitting wrong credentials shows Invalid email or password below the form.
How it works: The Server Action checks the credentials against the hardcoded demo user. If they match, it calls createSession, which sets the cookie. The Client Component uses useActionState to track the result and useRouter to navigate on success. In a real app, you would call redirect("/dashboard") inside the Server Action instead of using useEffect in the client. The client-side redirect is shown here to keep the form state visible during the demo .
Protecting Pages with a Data Access Layer
A data access layer is a server-only module that checks the session before returning protected data. You should call it from every page, layout, and Server Action that needs to know who the user is.
// app/dashboard/page.tsx
import { requireSession } from "@/lib/session";
export default async function DashboardPage() {
const session = await requireSession();
return (
<main>
<h1>Dashboard</h1>
<p>Welcome, {session.email}</p>
</main>
);
}
Browser shows: If you have a valid session, you see the dashboard with your email. If you do not, you are redirected to /login.
How it works: requireSession calls getSession, which reads and verifies the cookie. If there is no valid session, it redirects. This check happens on the server, before any data is fetched or rendered. Even if someone finds the URL, they cannot see the page without a valid cookie. This is the most important layer of protection .
Proxy.ts for Optimistic Redirects Only
In Next.js 16, the file previously called middleware.ts is now proxy.ts, and the exported function is named proxy . You can use it to redirect users who have no session cookie before they even reach a page. But it must not be your only security check.
// proxy.ts (project root or src/)
import { NextResponse } from "next/server";
import { type NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const session = request.cookies.get("session");
if (!session && request.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};
Output: A request to /dashboard without a session cookie is redirected to /login. A request with any session cookie is allowed through, even if the cookie is invalid.
How it works: proxy.ts runs before the route is rendered. It is a fast, coarse check that only looks at whether a cookie exists. It does not verify the signature or check if the user is allowed to see specific data. That is why it is called "optimistic." It improves the user experience by redirecting early, but the real authorization must happen in the data access layer. Relying on proxy.ts alone is dangerous because a misconfigured matcher can leave a route unprotected, and a forged cookie can pass a simple existence check .
Logout and Session Cleanup
Logging out means deleting the session cookie. A Server Action is the right place to do this because it can modify response headers.
// app/actions/auth.ts (add this function)
"use server";
import { deleteSession } from "@/lib/session";
import { redirect } from "next/navigation";
export async function logout() {
await deleteSession();
redirect("/login");
}
// app/dashboard/logout-button.tsx
"use client";
import { logout } from "../actions/auth";
export default function LogoutButton() {
return (
<form action={logout}>
<button type="submit">Log out</button>
</form>
);
}
Browser shows: Clicking "Log out" deletes the cookie and sends you to /login. Visiting /dashboard afterwards redirects you back to /login.
How it works: deleteSession calls cookieStore.delete("session"), which tells the browser to remove the cookie. The redirect function then navigates the user. The logout action is connected to a form, which means it works even without JavaScript, following the same progressive enhancement pattern as login.
Ready-Made Auth Libraries: A Short Overview
Building authentication from scratch is a good learning exercise, but production apps should use a maintained library. These libraries handle password hashing, session management, OAuth providers, and security updates for you.
- Auth.js (formerly NextAuth): A popular open-source library with many providers. As of late 2025, it is in security-patch mode, and its maintainers recommend Better Auth for new projects .
- Clerk: A hosted service with prebuilt UI components and a generous free tier. Good if you want to move fast and do not mind vendor lock-in.
- Better Auth: A newer open-source library that stores sessions in your database. It is actively developed and has become a common recommendation for new self-hosted projects .
Never store plain-text passwords. Use a vetted hashing library like bcrypt or argon2 to hash passwords before saving them to the database. Hashing is a one-way process: you can check a password against a hash, but you cannot turn the hash back into the password. Even if your database is leaked, attackers cannot read the original passwords .
Common Mistakes and Best Practices
Security disclaimer: The examples on this page are for education. They use a hardcoded user and a simple secret. A production system needs a real database, hashed passwords, HTTPS, a strong secret stored in environment variables, and a maintained auth library. Do not deploy demo authentication code.
- Relying on
proxy.tsas the only security check. A proxy check can be bypassed if the matcher misses a route or if a forged cookie passes a simple existence test. Always verify the session in the data access layer, close to where data is read or changed . - Forgetting to
awaitcookies(). In Next.js 16,cookies()returns a Promise. Callingcookies().set(...)withoutawaitthrows an error or silently fails, and your session cookie is never set . - Storing sensitive data in the cookie payload. A JWT is signed but not encrypted by default. Anyone can decode the payload and read it. Only put non-sensitive identifiers like a user ID in the token, never passwords or private data.
- Using a weak or hardcoded secret. The
SESSION_SECRETmust be a long random string stored in environment variables. If an attacker knows the secret, they can forge valid tokens and impersonate any user. - Not setting
HttpOnly,Secure, andSameSite. Without these flags, the cookie is vulnerable to XSS and CSRF attacks. Always set all three, and only usesecure: falsein local development without HTTPS . - Trying to set cookies in a Server Component. The
.set()method only works in a Server Action or Route Handler. In a Server Component, you can read cookies but not write them .
Real-World Example: A Protected Dashboard
This example brings the pieces together: a session helper, a login action, and a protected page. It uses a hardcoded demo user for clarity.
// lib/session.ts (simplified for this example)
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
const secretKey = new TextEncoder().encode(
process.env.SESSION_SECRET ?? "dev-only-secret"
);
export type SessionPayload = { userId: string; email: string };
export async function createSession(payload: SessionPayload) {
const token = await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("7d")
.sign(secretKey);
const cookieStore = await cookies();
cookieStore.set("session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});
}
export async function getSession(): Promise<SessionPayload | null> {
const token = (await cookies()).get("session")?.value;
if (!token) return null;
try {
const { payload } = await jwtVerify(token, secretKey);
return { userId: String(payload.userId), email: String(payload.email) };
} catch {
return null;
}
}
export async function requireSession(): Promise<SessionPayload> {
const session = await getSession();
if (!session) redirect("/login");
return session;
}
export async function deleteSession() {
(await cookies()).delete("session");
}
// app/actions/auth.ts
"use server";
import { createSession, deleteSession } from "@/lib/session";
import { redirect } from "next/navigation";
const DEMO_USER = {
id: "1",
email: "student@example.com",
password: "password123",
};
export type LoginState = { error: string | null };
export async function login(
_prevState: LoginState,
formData: FormData
): Promise<LoginState> {
const email = formData.get("email");
const password = formData.get("password");
if (typeof email !== "string" || typeof password !== "string") {
return { error: "Email and password are required" };
}
if (email !== DEMO_USER.email || password !== DEMO_USER.password) {
return { error: "Invalid email or password" };
}
await createSession({ userId: DEMO_USER.id, email: DEMO_USER.email });
redirect("/dashboard");
}
export async function logout() {
await deleteSession();
redirect("/login");
}
// app/dashboard/page.tsx
import { requireSession } from "@/lib/session";
import LogoutButton from "./logout-button";
export default async function DashboardPage() {
const session = await requireSession();
return (
<main>
<h1>Dashboard</h1>
<p>Logged in as: {session.email}</p>
<LogoutButton />
</main>
);
}
Line-by-line explanation:
lib/session.tsexports four helpers:createSession(signs and sets the cookie),getSession(reads and verifies the cookie),requireSession(redirects if no session), anddeleteSession(removes the cookie).app/actions/auth.tscontains the login and logout Server Actions. Login validates against the hardcoded demo user, creates the session, and redirects to/dashboard.app/dashboard/page.tsxis a Server Component that callsrequireSessionbefore rendering. If there is no valid session, the user is redirected to/login.- The logout button is a small Client Component that submits a form to the
logoutaction. The action deletes the cookie and redirects to/login.
Summary
- Next.js authentication with session cookies means checking credentials in a Server Action, signing a token, and storing it in an
HttpOnlycookie. cookies()is async in Next.js 16. Alwaysawaitit before reading or writing.- Authentication is who the user is. Authorization is what they can do. Check both on the server, close to your data.
- Use a data access layer with a
requireSessionhelper to protect pages and Server Actions. Useproxy.tsonly for optimistic redirects. - Never store plain-text passwords. Use a vetted hashing library, and prefer a maintained auth library for production.
- Set
HttpOnly,Secure, andSameSiteon every session cookie.
Now that you can identify users, the next step is storing their data. Continue with Next.js Database with Prisma.
Frequently Asked Questions
Why is cookies() async in Next.js 16?
Next.js 16 made cookies() asynchronous to support streaming and better performance. You must await it before calling .get() or .set(). If you forget, you may get a warning or an error saying the function was not awaited. Older versions of Next.js had a synchronous cookies() function, which is why some tutorials show it without await.
Can I set a cookie in a Server Component?
No. Server Components cannot modify response headers, and setting a cookie requires a Set-Cookie header. You can read cookies in a Server Component, but to set or delete them you must use a Server Action or a Route Handler. This is why login and logout logic belongs in Server Actions.
What is the difference between proxy.ts and middleware.ts?
In Next.js 16, middleware.ts was renamed to proxy.ts, and the exported function is now called proxy. The behavior is similar: it runs before a route is rendered and can redirect or rewrite requests. The rename clarifies that it is a network boundary, not a place for full authorization logic. Use it for optimistic checks only.
Do I need a database for Next.js authentication?
For production, yes. You need a database to store users, hashed passwords, and session records if you use database sessions. The tutorial uses a hardcoded demo user to focus on the mechanics. A real app would query the database in the login action, compare the password with a hash, and store sessions in the database or a signed cookie.
Why should I use an auth library instead of building my own?
Authentication has many edge cases: password hashing, session invalidation, OAuth flows, CSRF protection, and security updates. A maintained library handles these correctly and receives patches when vulnerabilities are found. Building your own is a good learning exercise, but for production, a library like Better Auth, Clerk, or Auth.js reduces risk and saves time.
Practice Exercises
Easy: Create a session helper
Write a getSession function that reads a cookie named "session" and returns its value, or null if the cookie is missing. Use cookies() from next/headers.
Show solution
// lib/session.ts
import { cookies } from "next/headers";
export async function getSession(): Promise<string | null> {
const cookieStore = await cookies();
return cookieStore.get("session")?.value ?? null;
}
cookies() is awaited, and the optional chaining operator returns null when the cookie is missing.
Easy: Add a logout action
Create a Server Action called logout that deletes the "session" cookie and redirects to /login.
Show solution
// app/actions/auth.ts
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export async function logout() {
const cookieStore = await cookies();
cookieStore.delete("session");
redirect("/login");
}
The .delete() method removes the cookie, and redirect sends the user to the login page.
Medium: Protect a page with requireSession
Create a requireSession function that calls getSession and redirects to /login if the session is null. Then use it in a /profile page.
Show solution
// lib/session.ts (add this function)
import { redirect } from "next/navigation";
export async function requireSession(): Promise<string> {
const session = await getSession();
if (!session) redirect("/login");
return session;
}
// app/profile/page.tsx
import { requireSession } from "@/lib/session";
export default async function ProfilePage() {
const session = await requireSession();
return <p>Session: {session}</p>;
}
requireSession centralizes the redirect logic, so every protected page uses the same check.
Challenge: Add a role check for authorization
Extend the session payload to include a role field ("user" or "admin"). Write a requireAdmin function that redirects to /dashboard if the session exists but the role is not "admin".
Show solution
// lib/session.ts (updated types and new function)
import { redirect } from "next/navigation";
export type SessionPayload = {
userId: string;
email: string;
role: "user" | "admin";
};
export async function requireAdmin(): Promise<SessionPayload> {
const session = await getSession();
if (!session) redirect("/login");
if (session.role !== "admin") redirect("/dashboard");
return session;
}
This separates authentication (is there a session?) from authorization (is the role admin?). Both checks happen on the server before any data is rendered.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
