Skip to content
Advertisement

How to define custom Express.js route for vite dev server

I am translating my app from webpack configuration into vite. My current webpack dev server has custom endopint configured for doing some stuff. I need to have this same endpoint in vite config as well. How to do this? How can I define an express.js route for vite dev server?

This endpoint is for loading environment variables from a service during runtime. The url for this route is /__variables.js.

I tried using this answer’s code

server.middlewares.use('/__variables.js', (req, res, next) => {
  console.log('hello we"re here')
  console.log(err, req, res)
  const variables = Object.keys(process.env).reduce(
      (prev, key) => {
          if(key.startsWith('REACT_APP_')) {
              prev[key] = process.env[key];
          }

          return prev;
      }
  , {});
  res
      .status(200)
      .type('.js')
      .set('Content-Type', 'application/javascript')
      .send(`window.__APP_VARIABLES__ = ${JSON.stringify(variables)}`)
  next();
});

but this throws an error res.status() is not a function. How to fix it?

Advertisement

Answer

According to the documentation for ViteDevServer, it’s based on Connect, not (as you seem to assume) Express, which means you can’t use any of the useful shortcut methods that Express provides on the request and response objects.

Instead, req will be an instance of http.ClientRequest and res an instance of http.ServerResponse.

Your Express-ish code will translate to this:

res
  .writeHead(200, { 'Content-Type': 'application/javascript' })
  .end(`window.__APP_VARIABLES__ = ${JSON.stringify(variables)}`);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement