Skip to content

Instantly share code, notes, and snippets.

@Rykuno
Created January 9, 2022 16:55
Show Gist options
  • Save Rykuno/8454639196916850cbc1b20326e4f78b to your computer and use it in GitHub Desktop.
Save Rykuno/8454639196916850cbc1b20326e4f78b to your computer and use it in GitHub Desktop.
NextJS: Cookie setting and unsetting
import { serialize, CookieSerializeOptions } from "cookie";
import { NextApiResponse } from "next";
/**
* This sets `cookie` using the `res` object
*/
interface Cookie {
name: string;
value: unknown;
options: CookieSerializeOptions | {};
}
export const setCookies = (res: NextApiResponse, cookies: Cookie[]) => {
const parsedCookies = cookies.map(({ name, value, options }) => {
const stringValue =
typeof value === "object" ? "j:" + JSON.stringify(value) : String(value);
if ("maxAge" in options) {
options.expires = new Date(Date.now() + options.maxAge);
options.maxAge /= 1000;
}
return serialize(name, stringValue, options);
});
res.setHeader("Set-Cookie", parsedCookies);
};
export const unsetCookies = (res: NextApiResponse, names: string[]) => {
const parsedCookies = names.map(name =>
serialize(name, "DONE", {
maxAge: 0,
path: "/"
})
);
res.setHeader("Set-Cookie", parsedCookies);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment