Cookies available on RSC are not available to the middleware #49444
Unanswered
rawnly
asked this question in
App Router
Replies: 3 comments 4 replies
-
Sounds like the same problem I have right now. Discussion: #49252 |
Beta Was this translation helpful? Give feedback.
4 replies
-
I found a solution how I can work with cookies which are sent via the middleware. Solution: middleware.ts import { NextRequest, NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";
export function contactMiddleware(
request: NextRequest,
response: NextResponse
) {
if (request.nextUrl.pathname == "/contact") {
const csrfToken = uuidv4();
const cookieOptions = {
name: "csrfToken",
value: csrfToken,
httpOnly: true,
maxAge: 0,
secure: true,
};
response.cookies.set(cookieOptions);
return response;
}
} page.tsx import { ResponseCookies } from "next/dist/compiled/@edge-runtime/cookies";
import { headers } from "next/headers";
export default function Page(props: any) {
const headersStore = headers();
const responseCookies = new ResponseCookies(headersStore as Headers);
const csrfTokenCookie = responseCookies.get("csrfToken");
const csrfToken = csrfTokenCookie ? csrfTokenCookie.value ?? "" : "";
return (<>{csrfToken}</>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
middleware.ts
} app/layout.tsx
getCookie
still unable to get cookie in layout.tsx that i updated in middleware.ts |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm writing a proxy endpoint to inject the jwt on in the requests sent to our API. Atm the jwt is stored inside a cookie, but even tho this is available via
cookies()
, when Ifetch
the proxy (which is inside the middleware) I cannot access any cookie viarequest.cookie.getAll()
(it returns[]
)The request is sent via fetch as the following
Proxy code:
EDIT: by adding
headers: headers()
to the fetch request seems to fix this behavior, but (at least for me) this feels wrong.Am I doing something wrong? (maybe with the credentials stuff?)
Beta Was this translation helpful? Give feedback.
All reactions