Cookies set in route handler not visible in middleware.
Answered
Chestnut-backed Chickadee posted this in #help-forum
Chestnut-backed ChickadeeOP
I have the below route handler.
and here is the middleware
the
import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { createAdminClient } from "@/lib/server/appwrite"
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url)
const userId = searchParams.get("userId")!!
const secret = searchParams.get("secret")!!
const { account } = await createAdminClient()
const session = await account.createSession(userId, secret)
console.log(session)
cookies().set("appwrite_session", session.secret, {
path: "/",
httpOnly: true,
sameSite: "strict",
secure: process.env.NODE_ENV === "production" ? true : false,
})
redirect("/dashboard")
}and here is the middleware
import { NextResponse, type NextRequest } from "next/server"
import { getLoggedInUser } from "./lib/server/appwrite"
import { cookies } from "next/headers"
export async function middleware(request: NextRequest) {
let response = NextResponse.next({
request: {
headers: request.headers,
},
})
const thing = cookies() // is empty
const user = await getLoggedInUser()
if (!user && request.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/sign-in", request.url))
}
if (
user &&
(request.nextUrl.pathname.startsWith("/sign-in") ||
request.nextUrl.pathname.startsWith("/sign-up"))
) {
return NextResponse.redirect(new URL("/dashboard", request.url))
}
return response
}
export const config = {
matcher: ["/dashboard", "/sign-in", "/sign-up"],
}the
getLoggedInUser method reads the cookie which was set in the route handler. It starts working after a refresh. What wrong am I doing?Answered by Toyger
hmm, may be a bug, hard to say, as workaround you can create some route handler like /dashboard_redirect that will redirect to dashboard, and then from your route handler where you set cookies change redirect to
so it will be additional hop, and at the moment when you'll get to dashboard page cookies should be set
redirect("/dashboard_redirect")so it will be additional hop, and at the moment when you'll get to dashboard page cookies should be set
29 Replies
Chestnut-backed ChickadeeOP
P.S: using nextjs 13, lemme know if an upgrade to 14 is required/ recommended
Hmmmm.
One sec
You have to do cookies().get('cookie name')
If your still in development phase I would def update to 14
Cookies() itself doesnt list all the cookies out by it self
you can do cookies().getAll() though
@Chestnut-backed Chickadee
Chestnut-backed ChickadeeOP
Yeah that is also empty @Jboncz
Can you show me your code?
Chestnut-backed ChickadeeOP
im inspecting that variable after attaching a debugger and it says empty
I've sent the code at the top ^
Oh sorry lol itll be tomorrow before I look, in bed
Chestnut-backed ChickadeeOP
no worries
@Chestnut-backed Chickadee im inspecting that variable after attaching a debugger and it says empty
Toyger
get cookies from request as it shown in docs https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
request.cookies.get('whatever_cookie')@Toyger get cookies from request as it shown in docs https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
js
request.cookies.get('whatever_cookie')
Chestnut-backed ChickadeeOP
yes that is correct
so the
await getLoggedInUser() has this code const session = cookies().get("appwrite_session")
if (!session || !session.value) {
throw new Error("No session")
}so it will try to get the cookie
its just the cookies are not available when accessed in middleware just after redirecting from route handler
once i refresh the page, it picks the cookies back up properly
@Chestnut-backed Chickadee its just the cookies are not available when accessed in middleware just after redirecting from route handler
Toyger
still try to access it directly from request, it can be available here after redirect
@Toyger still try to access it directly from request, it can be available here after redirect
Chestnut-backed ChickadeeOP
this is what i had changed
@Chestnut-backed Chickadee Click to see attachment
Toyger
hmm, may be a bug, hard to say, as workaround you can create some route handler like /dashboard_redirect that will redirect to dashboard, and then from your route handler where you set cookies change redirect to
so it will be additional hop, and at the moment when you'll get to dashboard page cookies should be set
redirect("/dashboard_redirect")so it will be additional hop, and at the moment when you'll get to dashboard page cookies should be set
Answer
Chestnut-backed ChickadeeOP
yeah that's what i did
but it feels wrong to do so
i just dont want people to be laughing at me