Next.js Discord

Discord Forum

Setting a cookie in route handler

Unanswered
neon posted this in #help-forum
Open in Discord
I've got this very basic authentication route handler under /api/admin_auth/login
import { NextRequest, NextResponse } from "next/server";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import { cookies } from "next/headers";

const validate = async (username: string, password: string) => {
  return (
    username === process.env.ADMIN_USERNAME &&
    (await bcrypt.compare(password, process.env.ADMIN_PASSWORD_HASH ?? ""))
  );
};

export async function POST(request: NextRequest) {
  const { username, password } = await request.json();

  const isValid = await validate(username, password);

  if (!isValid) {
    return NextResponse.json(
      { message: "Invalid credentials" },
      { status: 401 },
    );
  }

  const token = jwt.sign({ role: "admin" }, process.env.JWT_SECRET ?? "", {
    expiresIn: "1h",
  });

  console.log("BEFORE COOKIE");

  const cookieStore = await cookies();

  cookieStore.set("admin_auth_token", token, {
    httpOnly: process.env.NODE_ENV === "production",
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    maxAge: 3600,
    path: "/",
  });
  console.log("AFTER COOKIE");
  return NextResponse.json("Authentication successful", {
    status: 200,
  });
}

Even though I'm using cookies() function from next/headers inside a route handler, the cookie isn't set. Both "BEFORE COOKIE" and "AFTER COOKIE" are printed on the console, and I don't get any errors either...

P.S. I asked this yesterday as well but didn't get any response so I created a new ticket.

4 Replies

Asian black bear
Do not create duplicate threads for the same issue. You are however allowed to bump your thread once a day to gain visibility.
Asian black bear
Just like that. Messaging in a thread causes it to appear at the top of the thread list.
Ah, okay. Sorry for the duplicate, I'll delete my previous post