webpack-dev-middleware icon indicating copy to clipboard operation
webpack-dev-middleware copied to clipboard

Support History API urls

Open frederickfogerty opened this issue 11 years ago • 10 comments

Hey there,

I am using webpack-dev-middleware to develop a SPA, with an index.html which is programatically generated by webpack. With this plugin, if I navigate to anything other than / or /index.html, the middleware does not pick up the request, and the request fails.

For most people, something like this solves the problem:

app.get('*', function (req, res) {
  res.send(path.join(__dirname, 'index.html'))
}

but for previously mentioned reasons, this doesn't work. I have written this handler to catch urls missed by webpack-dev-middleware, but would look at adding this into the core.

app.use(function (req, res, next) {
  if (req.url.match(/^(\/[a-zA-Z-]+)+(.html)?(\?.+)?$/)) { // Just a regex I spun up to sort my use case
    devMiddleware(
      {
        url: '/index.html'
      },
      res,
      next
    )
  } else {
    next()
  }
})

Forgive me if I've completely missed a config flag or something - I have looked at the source and couldn't find anything.

I am happy to help write a PR to support this, especially since this will become more popular with react-transform becoming more popular.

Thanks for your help in advance

frederickfogerty avatar Sep 06 '15 22:09 frederickfogerty

webpack-dev-middleware has the middleware.fileSystem API that exposes the in-memory filesystem, which webpack put the generated files.

I'm not exactly familiar with express js, but this is my solution: https://gist.github.com/maman/8e91e6cb4ca9feaa4290

maman avatar Sep 13 '15 19:09 maman

@maman thank you, sir—this was just what I needed!

roblafeve avatar Oct 28 '15 04:10 roblafeve

I was trying to do that and it worked like a charm !

It would be cool to maybe get that when passing historyApiFallback: true

chollier avatar Nov 04 '15 22:11 chollier

  • gold -> Wondering if this should this be reference in docs.

anselmo avatar Nov 13 '15 22:11 anselmo

@maman you saved me a lot of time! thank you!

cef62 avatar Nov 17 '15 17:11 cef62

Thanks @maman. This should probably go in the docs somewhere. Leaving open until it's put in the docs

frederickfogerty avatar Nov 17 '15 21:11 frederickfogerty

Thank you for saving me a lot of time, even in 2016! I felt like this issue deserved a bump, and I'm looking forward for historyApiFallback to be added to the middleware's options.

kripod avatar Jun 09 '16 13:06 kripod

Oh no, it turns out that this solution doesn't work with koa...

kripod avatar Jun 09 '16 13:06 kripod

@kripod you can probably wrap the express middleware to make it work in koa

frederickfogerty avatar Jun 09 '16 21:06 frederickfogerty

I'll close this since #44 was also closed, for reasoning see that ticket.

SpaceK33z avatar Aug 30 '16 17:08 SpaceK33z