Vite dev server: adding middleware

brense

Rense Bakker

Posted on March 20, 2023

Vite dev server: adding middleware

While working on apps that will be deployed to Vercel, I have run into this situation several times, where I wanted to be able to start my api middleware together with the Vite dev server for local development. Normally you would run the api middleware separately using an express server for example and proxy requests from your Vite app to that server. However, since the Vite dev server can use express middleware, I wondered if it would be possible to eliminate the need to run a separate express server:

import express from 'express'
import { defineConfig, ViteDevServer } from 'vite'

const app = express()

app.get('/api', (req, res) => {
  res.send('Hello world!').end()
})

function expressPlugin() {
  return {
    name: 'express-plugin',
    configureServer(server: ViteDevServer) {
      server.middlewares.use(app)
    }
  }
}

export default defineConfig({
  plugins: [expressPlugin()]
})
Enter fullscreen mode Exit fullscreen mode

By default, the Vite dev server won't pass on any requests to our middleware, so the code above will not work. However, with a little trick using the proxy config, we can tell the dev server to let a certain request be handled elsewhere, or in this case, by our middleware:

import { ProxyOptions, ViteDevServer } from 'vite'

const proxy: Record<string, string | ProxyOptions> = {
  '/api': {} // proxy our /api route to nowhere
}

function expressPlugin() {
  return {
    name: 'express-plugin',
    config() {
      return {
        server: { proxy },
        preview: { proxy }
      }
    },
    configureServer(server: ViteDevServer) {
      server.middlewares.use(app)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if we run our dev server and go to the /api route, it will display our Hello world! response.

💖 💪 🙅 🚩
brense
Rense Bakker

Posted on March 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related