react-router icon indicating copy to clipboard operation
react-router copied to clipboard

Support webpack-dev-server historyApiFallback: true

Open fellz opened this issue 11 years ago • 42 comments

Hi I don't know exactly is this issue with webpack but i think so I have simple config for router

var ReactappApp = require('./ReactappApp');
var HelloWorld = require('./HelloWorld');
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;


var content = document.getElementById('content');

var Routes = (
  <Route path="/" handler={ReactappApp}>
    <Route name="hello" path="hello" handler={HelloWorld}/>
  </Route>
);
console.log(Routes);
Router.run(Routes,Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, content);
});

So i try to load HelloWorld component at /hello and get Cannot GET /hello So server doesn't see this route

I use grunt and connect also. Here is grunt task for webpack:

'webpack-dev-server': {
      options: {
        hot: true,
        port: 8000,
        webpack: webpackDevConfig,
        publicPath: '/assets/',
        contentBase: './<%= pkg.src %>/'
    }

and here is webpack config https://gist.github.com/fellz/b2cc0de81c7b1f5bf442#file-webpack-config

with historyApiFallback: true

'webpack-dev-server': {
      options: {
        hot: true,
        port: 8000,
        webpack: webpackDevConfig,
        publicPath: '/assets/',
        contentBase: './<%= pkg.src %>/',
        historyApiFallback: true
    }

it's loading ReactappApp instead of HelloWorld

p.s. react-router-component works as expected and perfectly well

fellz avatar Jan 12 '15 10:01 fellz

This is not the router's problem: Webpack just doesn't know you're using pushstate and tries to actually serve /hello from filesystem.

The proper way to do that is to run pushstate server separately and set contentBase to its port.

A hackish but simpler way to do that is to inject a middleware (note this relies on undocumented property and may stop working in future):

    server = new WebpackDevServer(webpack(config), {
      contentBase: contentBase,
      publicPath: config.output.publicPath,
      hot: true
    });

    server.app.use(function pushStateHook(req, res, next) {
      var ext = path.extname(req.url);
      if ((ext === '' || ext === '.html') && req.url !== '/') {
        req.pipe(request(localURL)).pipe(res);
      } else {
        next();
      }
    });

Can't say how to translate this to grunt task tho.

gaearon avatar Jan 12 '15 10:01 gaearon

@gaearon Ok thanks btw why react-router-components works fine with this stuff ?

fellz avatar Jan 12 '15 11:01 fellz

I don't know, it shouldn't. If server doesn't serve index.html on /hello, there's nothing any router can do about it.

gaearon avatar Jan 12 '15 11:01 gaearon

@gaearon well key diff in this historyApiFallback: true react-router-component works fine with this option and react-router is not ...

fellz avatar Jan 12 '15 11:01 fellz

I'm not sure what historyApiFallback is (couldn't find it in react-router-component docs) but you can fall back to Router.HashLocation if you'd like.

gaearon avatar Jan 12 '15 12:01 gaearon

@gaearon historyApiFallback is an option for webpack-dev-server that you familiar with ) look at the last line

'webpack-dev-server': {
      options: {
        hot: true,
        port: 8000,
        webpack: webpackDevConfig,
        publicPath: '/assets/',
        contentBase: './<%= pkg.src %>/',
        historyApiFallback: true
    }

fellz avatar Jan 12 '15 12:01 fellz

Ah, thanks. I didn't know dev server supports this. So you're saying it doesn't work with RR but works with RRC?

gaearon avatar Jan 12 '15 14:01 gaearon

@gaearon exactly

fellz avatar Jan 12 '15 14:01 fellz

I'll take a look, thanks for reporting!

gaearon avatar Jan 12 '15 14:01 gaearon

@gaearon do you know what the core issue is with historyApiFallback: true?

mjackson avatar Jan 15 '15 16:01 mjackson

I'll take a look now, sorry for delay

gaearon avatar Jan 15 '15 17:01 gaearon

I couldn't reproduce the problem. In my testing, historyApiFallback works fine with RR.

gaearon avatar Jan 15 '15 17:01 gaearon

I find historyApiFallback works with shallow routes but not deep routes, I'm not sure it has anything to do with react-router though. The reason seems to be requests to my app.js are not resolved to the root like other requests are? GET http://localhost:8080/orgs/-Jfah70YYREFxUpYaG4C/endpoints/app.js fails?

nelix avatar Jan 15 '15 21:01 nelix

I found a problem there have to configure routes properly like this:

var routes = [
    <Route path="/" handler={App} />,
    <Route path="/hello" handler={Hello} />
] 

but still RR doesn't work if you want your routes without hashes (Router.HistoryLocation)

  • historyApiFallback: true flag in webpack-dev-server options must be set

p.s. full project with code is here https://github.com/fellz/react-webpack-app

fellz avatar Jan 16 '15 10:01 fellz

https://github.com/webpack/react-starter uses pushstate and the router, so something must be up with your app. Let us know if you find what's wrong :)

ryanflorence avatar Feb 01 '15 06:02 ryanflorence

I just ran into this issue. You have to tell webpack to always serve up index.html. Here is an example, assuming your server.js file and index.html are both in the root of your project:

server.js

var webpack = require('webpack'),
    WebpackDevServer = require('webpack-dev-server'),
    config = require('./webpack.config'),
    path = require("path");

var server = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
});

// Important part. Send down index.html for all requests
server.use('/', function(req, res) {
  res.sendFile(path.join(__dirname+'/index.html'));
});

server.listen(3010, 'localhost', function (err, result) {
  if (err) {
    console.log(err);
  }

  console.log('Listening at localhost:3010');
});

marbemac avatar Feb 05 '15 01:02 marbemac

If you're like me and use html-webpack-plugin this works wonderfully:

var config = require('./webpack.config');
var http = require('http');
var path = require('path');
var url = require('url');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');

var server = new WebpackDevServer(webpack(config), config.devServer);

// Important part. Send down index.html for all requests
server.use('/', function (req, resp, next) {
  var opts = url.parse('http://localhost:8080');
  opts.method = req.method;
  opts.headers = req.headers;

  var myReq = http.request(opts, function (myRes) {
    var statusCode = myRes.statusCode;
    var headers = myRes.headers;
    var location = headers.location;

    if (200 !== statusCode) {
      next();

      return;
    }

    resp.writeHead(myRes.statusCode, myRes.headers);
    myRes.on('error', function (err) {
      next(err);
    });
    myRes.pipe(resp);
  });
  myReq.on('error', function (err) {
    next(err);
  });

  if (!req.readable) {
    myReq.end();
  } else {
    req.pipe(myReq);
  }
});

server.listen(8080, 'localhost', function() {
  console.log('Listening on http://localhost:' + server.get('port'));
});

stefanfisk avatar Feb 11 '15 20:02 stefanfisk

@nelix I ran into a similar issue. I am not yet using react-router, but the symptom matched to what is being described here. In my case, setting historyApiFallback: true worked when when the root url is loaded first, when I loaded some deep url, browser failed to load a few fonts. https://github.com/webpack/webpack/issues/443 gave me a hint so I tried adding __webpack_public_path__ = "/" in my main entry point. That fixed the deep link reload problem.

ramnivas avatar Mar 02 '15 19:03 ramnivas

Thanks @ramnivas

nelix avatar Mar 02 '15 21:03 nelix

Some of the examples above are very complicated. In most cases you can get this working simply by adding the following lines to your webpack.config.js file:

devServer: {
  historyApiFallback: true
}

I made an example app to help anyone else looking for a solution to this (like I was).

amacneil avatar Sep 28 '15 18:09 amacneil