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.