New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to use "parseCookies" function inside _.middleware.ts page in NextJS? #561
Comments
any update on this question? |
Unfortunately no, as for my case middlewares weren't really needed, I just stopped using them. But if you find a way to solve this problem, please let me know. |
@maticzav If I work on a PR to add Also, a note in the repo README specifying that |
Any update on this? At the moment we have to add some custom solutions like this. import type { CookieParseOptions } from 'cookie';
import type { NextRequest } from 'next/server';
import nookies from 'nookies';
import { getCookieNameByPrefix } from './cookie-helpers';
type Ctx = Parameters<typeof nookies.get>[0];
type CtxWithNextRequest = Pick<NonNullable<{ req: NextRequest } | Ctx>, 'req'>;
const isNextJsMiddlewareReq = (
req: CtxWithNextRequest['req']
): req is NextRequest =>
Boolean(req && 'cookies' in req && 'getAll' in req.cookies);
const getCookiesListFromMiddlewareReq = (req: CtxWithNextRequest['req']) => {
if (!isNextJsMiddlewareReq(req)) {
return;
}
const cookies = req?.cookies?.getAll().reduce(
(result: Parameters<typeof getCookieNameByPrefix>[0], { name, value }) => ({
...result,
[name]: value,
}),
{}
);
return cookies;
};
export const getServerCookie = (
cookieNamePrefix: string,
ctx: CtxWithNextRequest,
options: CookieParseOptions
) => {
const cookiesToUse =
getCookiesListFromMiddlewareReq(ctx.req) ||
nookies.get(ctx as Ctx, options);
const cookieName = getCookieNameByPrefix(cookiesToUse, cookieNamePrefix);
return cookieName && cookiesToUse[cookieName];
}; |
Hey, I'm running into some trouble trying to figure out how to use nookies inside a NextJS middleware. Inside of it, I have no access to the request context, but the function is still executed on the server-side. My code looks something like this:
How can I get my cookie inside of the middleware function?
The text was updated successfully, but these errors were encountered: