shellscape / webpack-plugin-serve

A Development Server in a Webpack Plugin
http://shellscape.org
Mozilla Public License 2.0
337 stars 49 forks source link

Adding custom headers #36

Closed kurtextrem closed 5 years ago

kurtextrem commented 5 years ago

webpack-dev-server and webpack-serve supported adding custom headers. Have I overlooked something or is this not supported here?

Thank you in advance.

shellscape commented 5 years ago

@kurtextrem great question, thanks for opening an issue about it. webpack-dev-server's headers option is some abstract sugar on top of express. While it's used, we determined it wasn't widely used. Since we run Koa under the hood in this plugin, it's very easy to wire up and has no restrictions on how you specify headers. Here's one way to accomplish this:

// webpack.config.js
module.exports = {
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) =>
        app.use(async (ctx, next) => {
          await next();
          ctx.set('X-Superhero', 'batman');
        })
    })
  ]
};

We'll add this as a recipe in as soon as we're able to. I'll also create a voting issue for direct support of an option for this, and if it reaches enough votes, we'll add a formal option for headers.

matheus1lva commented 5 years ago

Or you can use the proxy middleware and add any header when it gets the result from your api/mocked api.

module.exports = {
  ...,
  plugins: [
    new WebpackPluginServe({
      middleware: (app, builtins) => {
        app.use(builtins.proxy('/api', { 
          target: 'http://10.10.10.1:1337',
          onProxyRes: (proxyRes, req, res) => {
            proxyRes.headers['x-added'] = 'foobar' // add new header to response
          }
        }));
      }
    })
  ]
};

if you need headers in any other lifecycle, you can check the http-proxy-middleware docs to see the other methods.

shellscape commented 5 years ago

I have created a voting issue for the feature in #37

kurtextrem commented 5 years ago

Thank you Andrew and @PlayMa256 for the quick answers. Really helpful!

shellscape commented 5 years ago

Gonna close this one as resolved for now, but will reopen if anyone requests it.

shellscape commented 5 years ago

Added a recipe for this to our documentation in 2636d30