88038ca21f
Convert `api-routes-middleware` example to TypeScript to match Contribution docs. - Updated cookie util to match the [extending `res` with TypeScript Next.js docs](https://nextjs.org/docs/api-routes/api-middlewares#connectexpress-middleware-support) ## Documentation / Examples - [X] Make sure the linting passes by running `pnpm lint` - [X] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples) )
22 lines
576 B
TypeScript
22 lines
576 B
TypeScript
import type { NextApiResponse } from 'next'
|
|
import { serialize, CookieSerializeOptions } from 'cookie'
|
|
|
|
/**
|
|
* This sets `cookie` using the `res` object
|
|
*/
|
|
|
|
export const setCookie = (
|
|
res: NextApiResponse,
|
|
name: string,
|
|
value: unknown,
|
|
options: CookieSerializeOptions = {}
|
|
) => {
|
|
const stringValue =
|
|
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)
|
|
|
|
if (typeof options.maxAge === 'number') {
|
|
options.expires = new Date(Date.now() + options.maxAge * 1000)
|
|
}
|
|
|
|
res.setHeader('Set-Cookie', serialize(name, stringValue, options))
|
|
}
|