wasp/web/docs/advanced/middleware-config.md
Craig McIlwrath 60233dcbcc
Restructures docs (#1333)
Co-authored-by: Mihovil Ilakovac <mihovil@ilakovac.com>
Co-authored-by: Martin Šošić <Martinsos@users.noreply.github.com>
Co-authored-by: Filip Sodić <filip.sodic@gmail.com>
Co-authored-by: Filip Sodić <filip.sodic@fer.hr>
2023-08-11 16:47:49 +02:00

9.0 KiB

title
Configuring Middleware

import { ShowForTs } from '@site/src/components/TsJsHelpers';

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.

    :::note CORS 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.

    :::note JSON 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:

  1. global: here, any changes will apply by default to all operations (query and action) and api. This is helpful if you wanted to add support for multiple domains to CORS, for example.

:::caution Modifying global middleware Please 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. :::

  1. 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.
  2. 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 and GET, or to apply some middleware to a set of api routes.

Default Middleware Definitions

Below is the actual definitions of default middleware which you can override.

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:

app todoApp {
  // ...

  server: {
    setupFn: import setup from "@server/serverSetup.js",
    middlewareConfigFn: import { serverMiddlewareFn } from "@server/serverSetup.js"
  },
}
import cors from 'cors'
import config from '@wasp/config.js'

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 "@server/serverSetup.js",
    middlewareConfigFn: import { serverMiddlewareFn } from "@server/serverSetup.js"
  },
}
import cors from 'cors'
import type { MiddlewareConfigFn } from '@wasp/middleware'
import config from '@wasp/config.js'

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:

// ...

api webhookCallback {
  fn: import { webhookCallback } from "@server/apis.js",
  middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@server/apis.js",
  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 "@server/apis.js",
  middlewareConfigFn: import { webhookCallbackMiddlewareFn } from "@server/apis.js",
  httpRoute: (POST, "/webhook/callback"),
  auth: false
}
import express from 'express'
import { WebhookCallback } from '@wasp/apis/types'
import type { MiddlewareConfigFn } from '@wasp/middleware'

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
}

:::note 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:

// ...

apiNamespace fooBar {
  middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@server/apis.js",
  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 "@server/apis.js",
  path: "/foo/bar"
}
import express from 'express'
import type { MiddlewareConfigFn } from '@wasp/middleware'

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
}

:::note This gets installed at the router level for the path. Behind the scenes, this results in something like:

router.use('/foo/bar', fooBarNamespaceMiddleware)

:::