Skip to content

Add Express middleware function for Vite server #258

@chriscalo

Description

@chriscalo

Is your feature request related to a problem? Please describe.
For simple projects I like to integrate the local dev server with the API server. I still use Express, and with Vite using Koa, it seems to require significant contortions to get the Vite server running within my Express app.

It's also not clear to me how to ensure my dev and prod serving logic are exactly the same (save for file watching and HMR, obviously). I'd love to use a Vite-supplied server for file serving in prod.

Describe the solution you'd like
I particularly like how Nuxt offers a nuxt.render(req, res) function that can be used as an Express / Connect middleware function. It works great and is easy to integrate (from the Nuxt API docs):

const { loadNuxt, build } = require('nuxt')

const app = require('express')()
const isDev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 3000

async function start() {
  // We get Nuxt instance
  const nuxt = await loadNuxt(isDev ? 'dev' : 'start')

  // Render every route with Nuxt.js
  app.use(nuxt.render)

  // Build only in dev mode with hot-reloading
  if (isDev) {
    build(nuxt)
  }
  // Listen the server
  app.listen(port, '0.0.0.0')
  console.log('Server listening on `localhost:' + port + '`.')
}

start()

Similarly, Vite could offer expressRender(req, res, next), koaRender(ctx, next), etc methods. Here's one idea of what that could look like:

const { build, Server } = require('vite')

const app = require('express')()
const isDev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 3000
const viteConfig = require("../vite.config.js")

const viteServer = new Server(viteConfig)
app.use(viteServer.expressRender)

if (isDev) {
  build(viteConfig)
}

// Listen the server
app.listen(port, '0.0.0.0')
console.log('Server listening on `localhost:' + port + '`.')

Describe alternatives you've considered

  • I tried rewriting my Express modules in Koa, and it just feels like too much effort.
  • I wasn't able to find a koa-to-express adapter to embed the Vite dev server in my express app.
  • I wasn't sure how to use a proxy to "merge" the Vite server and my Express server.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions