Skip to content

Instantly share code, notes, and snippets.

@ryanoglesby08
Last active April 4, 2024 13:25
Show Gist options
  • Star 70 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save ryanoglesby08/1e1f49d87ae8ab2cabf45623fc36a7fe to your computer and use it in GitHub Desktop.
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.
/*
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);
@cloudcompute
Copy link

cloudcompute commented Jan 14, 2022

Hi @ryanoglesby08

Thank you so much for your reply and letting me know about these resources. In the future, if I have any questions, I will surely write over the discussion forums.

@shubhamkr1
Copy link

shubhamkr1 commented Feb 10, 2022

Hi @ryanoglesby08
what is the folder structure that is assumed that your project has, in order to use this piece of code ?

@TulshiDas39
Copy link

Thanks.

@aderchox
Copy link

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