APIs

Building a simple Authentication in Nextjs part 4 Logout logic

Logging out requires two steps: 1. Remove the session token from the database. 2. Delete the session token from the cookie store. Recall that cookies are small pieces of information that the server sends to the browser. They are sent through the HTTP `Set-Cookie` header and are automatically included in future requests by the browser.

KUZUE
June 25, 2026
2 min read
4 views

Logging Out a User

Logging out requires two steps:

  1. Remove the session token from the database.
  2. Delete the session token from the cookie store.

Recall that cookies are small pieces of information that the server sends to the browser. They are sent through the HTTP Set-Cookie header and are automatically included in future requests by the browser.

Accessing Cookies in Next.js

In Next.js, you can access cookies by importing cookies from next/headers:

ts
import { cookies } from "next/headers";

const cookieStore = await cookies();

You can set a cookie like this:

ts
cookieStore.set("sessionToken", "1234567", {
  httpOnly: true,
  secure: true,
  sameSite: "lax",
  path: "/",
  expires: expiresAt,
});

Cookie Options

  • httpOnly: true prevents JavaScript from accessing the cookie through document.cookie.
  • secure: true ensures the cookie is only sent over HTTPS.
  • sameSite: "lax" helps protect against CSRF attacks.
  • path: "/" makes the cookie available throughout the application.
  • expires specifies when the cookie should expire.

Logout Route

ts
import prisma from "@/app/lib/prisma";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  try {
    const cookieStore = await cookies();

    const sessionToken =
      cookieStore.get("sessionToken");

    if (
      sessionToken &&
      sessionToken.value
    ) {
      try {
        await prisma.session.delete({
          where: {
            sessionToken:
              sessionToken.value,
          },
        });

        console.log(
          "Deleted token",
          sessionToken
        );
      } catch (error) {
        console.log(
          "Error deleting session"
        );

        return NextResponse.json({
          success: false,
          error: "Unable to delete session",
        });
      }
    }

    cookieStore.delete("sessionToken");

    return NextResponse.json(
      {
        success: true,
        message:
          "Deleted successfully",
      },
      { status: 200 }
    );
  } catch (error) {
    console.log("Error logging out");

    return NextResponse.json(
      {
        success: false,
        error: "Unable to log out",
      },
      { status: 500 }
    );
  }
}

We first extract the sessionToken from the cookie store:

ts
const sessionToken =
  cookieStore.get("sessionToken");

If the token exists, we delete the corresponding session record from the database:

ts
await prisma.session.delete({
  where: {
    sessionToken:
      sessionToken.value,
  },
});

Finally, we remove the cookie from the browser:

ts
cookieStore.delete("sessionToken");

At this point, the session no longer exists in the database, and the browser no longer has a valid session token, effectively logging the user out.

Comments (0)

No comments yet. Be the first to share your thoughts.