index.ts
This file
Path
src/middleware/cors/index.ts
164 lines · 5.3 KiB · TypeScript
Last changed by
fix(cors): append Origin to Vary header on OPTIONS preflight (#5235)Nanasibefore adoption8bf03c3
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–30why, one step back1/**2 * @module3 * CORS Middleware for Hono.4 */56import type { Context } from '../../context'7import type { MiddlewareHandler } from '../../types'89type CORSOptions = {10 origin?:11 | string12 | string[]13 | ((14 origin: string,15 c: Context16 ) => Promise<string | undefined | null> | string | undefined | null)17 allowMethods?: string[] | ((origin: string, c: Context) => Promise<string[]> | string[])18 allowHeaders?: string[]19 maxAge?: number20 credentials?: boolean21 exposeHeaders?: string[]22}2324/**25 * CORS Middleware for Hono.26 *27 * @see {@link https://hono.dev/docs/middleware/builtin/cors}28 *29 * @param {CORSOptions} [options] - The options for the CORS middleware.30 * @param {string | string[] | ((origin: string, c: Context) => Promise<string | undefined | null> | string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 31why, one step back31 * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']] - The value of "Access-Control-Allow-Methods" CORS header.Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 32–65why, one step back32 * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.33 * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.34 * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.35 * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header.36 * @returns {MiddlewareHandler} The middleware handler function.37 *38 * @example39 * ```ts40 * const app = new Hono()41 *42 * app.use('/api/*', cors())43 * app.use(44 * '/api2/*',45 * cors({46 * origin: 'http://example.com',47 * allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],48 * allowMethods: ['POST', 'GET', 'OPTIONS'],49 * exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],50 * maxAge: 600,51 * credentials: true,52 * })53 * )54 *55 * app.all('/api/abc', (c) => {56 * return c.json({ success: true })57 * })58 * app.all('/api2/abc', (c) => {59 * return c.json({ success: true })60 * })61 * ```62 */63export const cors = (options?: CORSOptions): MiddlewareHandler => {64 const opts = {65 origin: '*',Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
line 66why, one step back66 allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'],Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 67–71why, one step back67 allowHeaders: [],68 exposeHeaders: [],69 ...options,70 } satisfies CORSOptions71perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 72–74why, one step back72 const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(',') : undefined73 const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(',') : undefined74Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 75–90why, one step back75 const findAllowOrigin = ((optsOrigin) => {76 if (typeof optsOrigin === 'string') {77 if (optsOrigin === '*') {78 return () => optsOrigin79 } else {80 return (origin: string) => (optsOrigin === origin ? origin : null)81 }82 } else if (typeof optsOrigin === 'function') {83 return optsOrigin84 } else {85 return (origin: string) => (optsOrigin.includes(origin) ? origin : null)86 }87 })(opts.origin)8889 const findAllowMethods = ((optsAllowMethods) => {90 if (typeof optsAllowMethods === 'function') {perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
line 91why, one step back91 return async (origin: string, c: Context) => (await optsAllowMethods(origin, c)).join(',')Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 92why, one step back92 } else if (Array.isArray(optsAllowMethods)) {perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 93–94why, one step back93 const methodsStr = optsAllowMethods.join(',')94 return () => methodsStrMerge commit from forkYusuke Wadabefore adoptionf0b094d
line 95why, one step back95 } else {perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
line 96why, one step back96 return () => ''Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 97–113why, one step back97 }98 })(opts.allowMethods)99100 return async function cors(c, next) {101 function set(key: string, value: string) {102 c.res.headers.set(key, value)103 }104105 const allowOrigin = await findAllowOrigin(c.req.header('origin') || '', c)106 if (allowOrigin) {107 set('Access-Control-Allow-Origin', allowOrigin)108 }109110 if (opts.credentials) {111 set('Access-Control-Allow-Credentials', 'true')112 }113perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 114–115why, one step back114 if (exposeHeadersStr) {115 set('Access-Control-Expose-Headers', exposeHeadersStr)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 116–119why, one step back116 }117118 if (c.req.method === 'OPTIONS') {119 if (opts.origin !== '*') {fix(cors): append Origin to Vary header on OPTIONS preflight (#5235)Nanasibefore adoption8bf03c3
line 120why, one step back120 c.res.headers.append('Vary', 'Origin')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 121–127why, one step back121 }122123 if (opts.maxAge != null) {124 set('Access-Control-Max-Age', opts.maxAge.toString())125 }126127 const allowMethods = await findAllowMethods(c.req.header('origin') || '', c)perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 128–129why, one step back128 if (allowMethods) {129 set('Access-Control-Allow-Methods', allowMethods)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 130–131why, one step back130 }131perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 132–133why, one step back132 let headersStr = allowHeadersStr133 if (!headersStr) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 134–135why, one step back134 const requestHeaders = c.req.header('Access-Control-Request-Headers')135 if (requestHeaders) {perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 136–139why, one step back136 headersStr = requestHeaders137 .split(',')138 .map((h) => h.trim())139 .join(',')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 140–141why, one step back140 }141 }perf(cors): pre-join static array header options during initialization (#5210)Nanasibefore adoptiona1e4ac7
lines 142–143why, one step back142 if (headersStr) {143 set('Access-Control-Allow-Headers', headersStr)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 144–164why, one step back144 c.res.headers.append('Vary', 'Access-Control-Request-Headers')145 }146147 c.res.headers.delete('Content-Length')148 c.res.headers.delete('Content-Type')149150 return new Response(null, {151 headers: c.res.headers,152 status: 204,153 statusText: 'No Content',154 })155 }156 await next()157158 // Suppose the server sends a response with an Access-Control-Allow-Origin value with an explicit origin (rather than the "*" wildcard).159 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin160 if (opts.origin !== '*') {161 c.header('Vary', 'Origin', { append: true })162 }163 }164}