There may be occasion that we need to host the bundled static one-page web client on our own Node.js web server. The article describe the issues of API fall back to the app and other static file sourcing.
The app is developed with webpack dev server with history api fallback
on. History api fallback is exceptionally useful for a single page app, in which any url entry will be directed to the source file while the date transmitted in the path is retrieved as one of the source of information.
Webpack in Production
Once we build the file into production, the webpack-dev-server is no longer suitable. There is not native support of this function in node.If we enable an node server and make the index page up. Any url other than the main page will return 404 not found error.
The solution is making use of Express, a very light wight node web framework. What’s more, express-history-api-fallback
Web server after the bundling
After we buiild the project, we shall get a bunch of bundled files, including the entry point index.html
, and a lot of other files depending on how you define the webpack config. Putting the file on a server without a proper setting, the entry website somehow works with its own source code as we enter the index.html. But it is likely to have problems clients stating that source file cant accept reading of file in file format, but serving from a web server.
My approach is to create a separete repository storing about the bundled files and the production web servert
Create a new node server
In index.js
const fallback = require('express-history-api-fallback')
var history = require('connect-history-api-fallback');
const express = require('express')
const app = express()
const root = `${__dirname}/`
app.use(history());
app.use(express.static(root))
app.use(fallback(root, { root: root }))
app.listen(3000, () => console.log('Example app listening on port 3000'))
Hosting the static bundled client source file on the server with api fallback could be one approach.
It is more common to host in static web hosting, S3 for static web hosting with CloudFront CDN, for example, generally solve the above problem along with other benefits.
Leave a Reply