Serving our production build
We can serve our production build of the front end through Express.js. This approach is not great for development purposes but is useful for testing the build process and seeing how our live application will act.
Again, replace the previous routing example with the following:
import path from 'path';
const root = path.join(__dirname, '../../');
app.use('/', express.static(path.join(root, 'dist/client')));
app.use('/uploads', express.static(path.join(root, 'uploads')));
app.get('/', (req, res) => {
res.sendFile(path.join(root, '/dist/client/index.html'));
});
The path module offers many functionalities for working with the directory structures.
We use the global __dirname variable to get our project's root directory. The variable holds the path of the current file. Using path.join with ../../ and __dirname gives us the real root of our project.
Express.js provides the use function which runs a series of commands when a given path matches. When executing this function without a path, it is executed for every request.
We use this feature to serve our static files (the avatar images) with express.static. They include bundle.js and bundle.css, created by npm run client:build.
In our case, we first pass '/' with express.static following it. The result of this is that all files and folders in dist are served beginning with '/'. Other paths in the first parameter of app.use, such as '/example', would lead to the result that our bundle.js would be downloadable under '/example/bundle.js' instead.
For example, all avatar images are served under '/uploads/'.
We are now prepared to let the client download all necessary files. The initial route for our client is '/' specified by app.get. The response to this path is index.html. We run res.sendFile and the file path to return this file—that is all we have to do here.
Be sure to execute npm run client:build first. Otherwise, you will receive an error message that these files were not found. Furthermore, when running npm run client, the dist folder is deleted, so you have to rerun the build process.
Refreshing the browser now presents you with the post feed and form from Chapter 1, Preparing Your Development Environment.
The next section focuses on the great functionality of middleware functions in Express.js.