Last active
June 21, 2024 14:11
-
-
Save ryanoglesby08/1e1f49d87ae8ab2cabf45623fc36a7fe to your computer and use it in GitHub Desktop.
A node.js SPA server that serves static files and an index.html file for all other routes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Incredibly simple Node.js and Express application server for serving static assets. | |
DON'T USE THIS IN PRODUCTION! | |
It is meant for learning purposes only. This server is not optimized for performance, | |
and is missing key features such as error pages, compression, and caching. | |
For production, I recommend using an application framework that supports server-side rendering, | |
such as Next.js. https://nextjs.org | |
Or, if you do indeed want a Single Page App, the Create React App deployment docs contain a lot | |
of hosting options. https://create-react-app.dev/docs/deployment/ | |
*/ | |
const express = require('express'); | |
const path = require('path'); | |
const port = process.env.PORT || 8080; | |
const app = express(); | |
// serve static assets normally | |
app.use(express.static(__dirname + '/dist')); | |
// handle every other route with index.html, which will contain | |
// a script tag to your application's JavaScript file(s). | |
app.get('*', function (request, response) { | |
response.sendFile(path.resolve(__dirname, 'index.html')); | |
}); | |
app.listen(port); | |
console.log("server started on port " + port); |
Thanks.
Thanks.
(Just realized you haven't posted on your blog in the past 4 years, considering the quality of your content, I recommend continuing it, I've subscribed through RSS.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @ryanoglesby08
what is the folder structure that is assumed that your project has, in order to use this piece of code ?