A rewrite of expressjs/cors module.
HTTP cors header middleware.
pnpm i @tinyhttp/corsimport { cors } from '@tinyhttp/cors'Returns the CORS middleware with the settings specified in the parameters
origin: Can be a string defining theAccess-Control-Allow-Originvalue, a boolean which if set to true sets the header to'*', a Regex type, an array (for multiple origins) or a function which contains the request and response as parameters and must return the value for theAccess-Control-Allow-Originheadermethods: Array of method names which define theAccess-Control-Allow-Methodsheader, default to all the most common methods (GET,HEAD,PUT,PATCH,POST,DELETE)allowedHeaders: Configures theAccess-Control-Allow-HeadersCORS header. Expects an array (ex: ['Content-Type','Authorization']).exposedHeaders: Configures theAccess-Control-Expose-HeadersCORS header. If not specified, no custom headers are exposedcredentials: Configures theAccess-Control-Allow-CredentialsCORS header. Set to true to pass the header, otherwise it is omitted.maxAge: Configures theAccess-Control-Max-AgeCORS header. Set to an integer to pass the header, otherwise it is omitted.optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.preflightContinue: Set 204 and finish response iftrue, callnextif false.
The default configuration is:
{
"origin": "*",
"methods": ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
"optionsSuccessStatus": 204,
"preflightContinue": false
}import { App } from '@tinyhttp/app'
import { cors } from '@tinyhttp/cors'
const app = new App()
app
.use(cors({ origin: 'https://myfantastic.site/' }))
.options('*', cors())
.get('/', (req, res) => {
res.send('The headers contained in my response are defined in the cors middleware')
})
.listen(3000)