Skip to main content

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores

r/nextjs

members
online


I need help: Middleware cannot read cookies in production but works fine locally. I need help: Middleware cannot read cookies in production but works fine locally.
Help Noob

I have an app with a simple auth setup. The auth page hits an API route I created in the next API folder. If the conditions pass, I set a cookie, see below

export async function POST(request: NextRequest) {
  const body = await request.json();

  if (conditions_not_met) {
    return NextResponse.json({ success: false }, { status: 400 });
  }
  await createAuthCookie("some_string");

  return NextResponse.json({ success: true }, { status: 200 });
}

createAuthCookie is just a server action that runs this

cookies().set({
name: "name",
value: value,
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
});

In my middleware, I do some simple checks that just prevents users from view all other pages if not authenticated and redirects to the login page.

export default async function middleware(req: NextRequest) {
  let authenticated = cookies().get("cookie_name");

  if (req.nextUrl.pathname.startsWith("/_next")) {
    return NextResponse.next();
  }

  if (!authenticated) {
    console.error("Not authenticated");
    return NextResponse.redirect(process.env.AUTH_UI_URL!);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|login|favicon.ico).*)",
  ],
};

this all works fine locally but not in production which means all users are stuck on login page, am I missing something fundamental?

*Additionally, I can see the cookie being set in production, but the middleware just reads undefined no matter what I try.


Make your next big move with Photoshop. Everyone can scale.
Make your next big move with Photoshop. Everyone can scale.


Can anyone help me understand how to implement something like this in NextJs? I've been scouring the internet but can't find any tutorial or docs to help me figure out how to achieve a scrolling effect like the one shown in video (source: cypress.io) Can anyone help me understand how to implement something like this in NextJs? I've been scouring the internet but can't find any tutorial or docs to help me figure out how to achieve a scrolling effect like the one shown in video (source: cypress.io)
Help Noob