Unverified Commit 88038ca2 authored by Max Proske's avatar Max Proske Committed by GitHub

chore(examples): Convert `api-routes-middleware` example to TypeScript (#38358)

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)
)
parent 5145c2d5
...@@ -32,3 +32,6 @@ yarn-error.log* ...@@ -32,3 +32,6 @@ yarn-error.log*
# vercel # vercel
.vercel .vercel
# typescript
*.tsbuildinfo
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
...@@ -6,10 +6,16 @@ ...@@ -6,10 +6,16 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"cookie": "0.4.0", "cookie": "^0.5.0",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "^18.2.0",
"react-dom": "^17.0.2", "react-dom": "^18.2.0",
"swr": "0.1.18" "swr": "^1.3.0"
},
"devDependencies": {
"@types/node": "^18.0.2",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"typescript": "^4.7.4"
} }
} }
import cookies from '../../utils/cookies'
const handler = (req, res) => {
// The cookie middleware will add the `set-cookie` header
res.cookie('Next.js', 'api-middleware!')
// Return the `set-cookie` header so we can display it in the browser and show that it works!
res.end(res.getHeader('Set-Cookie'))
}
export default cookies(handler)
import type { NextApiRequest, NextApiResponse } from 'next'
import { setCookie } from '../../utils/cookies'
export default function handler(_req: NextApiRequest, res: NextApiResponse) {
// Calling our pure function using the `res` object, it will add the `set-cookie` header
setCookie(res, 'Next.js', 'api-middleware!')
// Return the `set-cookie` header so we can display it in the browser and show that it works!
res.end(res.getHeader('Set-Cookie'))
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
import { serialize } from 'cookie'
/**
* This sets `cookie` on `res` object
*/
const cookie = (res, 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
}
res.setHeader('Set-Cookie', serialize(name, String(stringValue), options))
}
/**
* Adds `cookie` function on `res.cookie` to set cookies for response
*/
const cookies = (handler) => (req, res) => {
res.cookie = (name, value, options) => cookie(res, name, value, options)
return handler(req, res)
}
export default cookies
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))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment