Configuring Middleware
Wasp comes with a minimal set of useful Express middleware in every application. While this is good for most users, we realize some may wish to add, modify, or remove some of these choices both globally, or on a per-api
/path basis.
Default Global Middleware 🌍
Wasp's Express server has the following middleware by default:
Helmet: Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it's a good start.
CORS: CORS is a package for providing a middleware that can be used to enable CORS with various options.
noteCORS middleware is required for the frontend to communicate with the backend.
Morgan: HTTP request logger middleware.
express.json (which uses body-parser): parses incoming request bodies in a middleware before your handlers, making the result available under the
req.body
property.noteJSON middlware is required for Operations to function properly.
express.urlencoded (which uses body-parser): returns middleware that only parses urlencoded bodies and only looks at requests where the
Content-Type
header matches the type option.cookieParser: parses Cookie header and populates
req.cookies
with an object keyed by the cookie names.
Customization
You have three places where you can customize middleware:
global: here, any changes will apply by default to all operations (
query
andaction
) andapi
. This is helpful if you wanted to add support for multiple domains to CORS, for example.Modifying global middlewarePlease treat modifications to global middleware with extreme care as they will affect all operations and APIs. If you are unsure, use one of the other two options.
per-api: you can override middleware for a specific api route (e.g.
POST /webhook/callback
). This is helpful if you want to disable JSON parsing for some callback, for example.per-path: this is helpful if you need to customize middleware for all methods under a given path.
- It's helpful for things like "complex CORS requests" which may need to apply to both
OPTIONS
andGET
, or to apply some middleware to a set ofapi
routes.
- It's helpful for things like "complex CORS requests" which may need to apply to both
Default Middleware Definitions
Below is the actual definitions of default middleware which you can override.
- JavaScript
- TypeScript
const defaultGlobalMiddleware = new Map([
['helmet', helmet()],
['cors', cors({ origin: config.allowedCORSOrigins })],
['logger', logger('dev')],
['express.json', express.json()],
['express.urlencoded', express.urlencoded({ extended: false })],
['cookieParser', cookieParser()]
])
export type MiddlewareConfig = Map<string, express.RequestHandler>
// Used in the examples below 👇
export type MiddlewareConfigFn = (middlewareConfig: MiddlewareConfig) => MiddlewareConfig
const defaultGlobalMiddleware: MiddlewareConfig = new Map([
['helmet', helmet()],
['cors', cors({ origin: config.allowedCORSOrigins })],
['logger', logger('dev')],
['express.json', express.json()],
['express.urlencoded', express.urlencoded({ extended: false })],
['cookieParser', cookieParser()]
])
1. Customize Global Middleware
If you would like to modify the middleware for all operations and APIs, you can do something like:
- JavaScript
- TypeScript
app todoApp {
// ...
server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
import cors from 'cors'
import { config } from 'wasp/server'
export const serverMiddlewareFn = (middlewareConfig) => {
// Example of adding extra domains to CORS.
middlewareConfig.set('cors', cors({ origin: [config.frontendUrl, 'https://example1.com', 'https://example2.com'] }))
return middlewareConfig
}
app todoApp {
// ...
server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
import cors from 'cors'
import { config, type MiddlewareConfigFn } from 'wasp/server'
export const serverMiddlewareFn: MiddlewareConfigFn = (middlewareConfig) => {
// Example of adding an extra domains to CORS.
middlewareConfig.set('cors', cors({ origin: [config.frontendUrl, 'https://example1.com', 'https://example2.com'] }))
return middlewareConfig
}
2. Customize api
-specific Middleware
If you would like to modify the middleware for a single API, you can do something like:
- JavaScript
- TypeScript
// ...
api webhookCallback {
fn: import { webhookCallback } from "@src/apis",
middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@src/apis",
httpRoute: (POST, "/webhook/callback"),
auth: false
}
import express from 'express'
export const webhookCallback = (req, res, _context) => {
res.json({ msg: req.body.length })
}
export const webhookCallbackMiddlewareFn = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')
middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw({ type: '*/*' }))
return middlewareConfig
}
// ...
api webhookCallback {
fn: import { webhookCallback } from "@src/apis",
middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@src/apis",
httpRoute: (POST, "/webhook/callback"),
auth: false
}
import express from 'express'
import { type WebhookCallback } from 'wasp/server/api'
import { type MiddlewareConfigFn } from 'wasp/server'
export const webhookCallback: WebhookCallback = (req, res, _context) => {
res.json({ msg: req.body.length })
}
export const webhookCallbackMiddlewareFn: MiddlewareConfigFn = (middlewareConfig) => {
console.log('webhookCallbackMiddlewareFn: Swap express.json for express.raw')
middlewareConfig.delete('express.json')
middlewareConfig.set('express.raw', express.raw({ type: '*/*' }))
return middlewareConfig
}
This gets installed on a per-method basis. Behind the scenes, this results in code like:
router.post('/webhook/callback', webhookCallbackMiddleware, ...)
3. Customize Per-Path Middleware
If you would like to modify the middleware for all API routes under some common path, you can define a middlewareConfigFn
on an apiNamespace
:
- JavaScript
- TypeScript
// ...
apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}
export const fooBarNamespaceMiddlewareFn = (middlewareConfig) => {
const customMiddleware = (_req, _res, next) => {
console.log('fooBarNamespaceMiddlewareFn: custom middleware')
next()
}
middlewareConfig.set('custom.middleware', customMiddleware)
return middlewareConfig
}
// ...
apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}
import express from 'express'
import { type MiddlewareConfigFn } from 'wasp/server'
export const fooBarNamespaceMiddlewareFn: MiddlewareConfigFn = (middlewareConfig) => {
const customMiddleware: express.RequestHandler = (_req, _res, next) => {
console.log('fooBarNamespaceMiddlewareFn: custom middleware')
next()
}
middlewareConfig.set('custom.middleware', customMiddleware)
return middlewareConfig
}
This gets installed at the router level for the path. Behind the scenes, this results in something like:
router.use('/foo/bar', fooBarNamespaceMiddleware)