-
-
Save ryanoglesby08/1e1f49d87ae8ab2cabf45623fc36a7fe to your computer and use it in GitHub Desktop.
/* | |
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); |
Wonderful answers. Helped me learn a lot. Thank you so much.
2 more Qs, just need confirmation from you..
a. A GraphQL request can be sent to the Apollo GraphQL server using either HTTP GET or POST. When your backend code has a GraphQL API endpoint that is served using HTTP Get, the request, let's say, /graphql/getUsers will also land up to the app.get("*", ...). Instead it should invoke the route handler.. app.Get("graphql/getUsers", ..)
Therefore, in this case, we need to modify the app.get("", ..) so that it should serve index.html for all routes except those that begin with /graphql. To exclude these /graphql routes, we can use a regular expression instead of the asterisk ().
Am I right?
b. The following line of code serves both a. index.html and b. other static assets like bundle.js, etc.
app.use(express.static(path.join(__dirname, 'dist')));
I think it is better if we do not let the above code to serve index.html using this code:
var options = { index: false }
app.use(express.static(path.join(__dirname, 'dist'), options)); // now serves files like bundle.js, bundle.css, *.png, only
Let the route handler app.get("*", ...) alone serve index.html.
Does this make sense?
You're welcome, glad I can help you out.
re: GraphQL routes
If you want to add additional routing to this server, you could add additional router methods before the catch all.
I recommend following the Express docs on this one. https://expressjs.com/en/4x/api.html#router
// handle static assets
app.use(express.static(path.join(__dirname, 'dist')));
// handle graphql requests
app.get('/graphql', function (request, response) {
// do stuff...
});
// handle everything else
app.get('*', function (request, response) {
response.sendFile(path.resolve(__dirname, 'index.html'));
});
Let the route handler app.get("*", ...) alone serve index.html.
express.static
only looks at the dist directory, so it is not handling the index.html file. If it is, then nested routes such as www.my-site.com/foo/bar
will break unless you also change the path.resolve(__dirname, 'index.html')
line to also point to dist. This is why I recommend the index.html file be outside of dist.
I think with the current setup, the express.static
middleware will attempt to handle a request for the index.html file, but since the fallthrough
option is true by default, it won't find it and will fallthrough to the next middleware and will eventually get handled by the catch all route.
You can certainly add that index: false
option, but if your index.html file is outside of the dist directory you don't really need it.
Thank you for the quick response.
When CRA
(create-react-app) creates a production build, it keeps the generated index.html inside the build folder.
A. CRA creates a production build having the following contents.
Taken from: https://create-react-app.dev/docs/production-build/
npm run build creates a build directory with a production build of your app. Inside the build/static
directory will be your JavaScript and CSS files.
The index.html lies in the build folder itself.
..
B. express.static
serves all kind of files including html, css, jpg, css residing in the public folder and its sub-folders.
Taken from: https://expressjs.com/en/starter/static-files.html
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/hello.html
..
C. Don't allow
express,static to serve index.html
Taken from: https://stackoverflow.com/questions/48056038/express-static-serves-index-html-how-to-deny-it
var options = {
index: false
}
app.use(express.static(path.join(__dirname, 'dist'), options));
Final Answer based on these 3 points and your inputs:
Our index.html file is "not" outside of the dist directory.
const pathToBuildFolder = path.join(__dirname, "../../web/build");
// Serve all except index.html
const options = {
index: false
}
app.use(express.static(pathToBuildFolder, options));
// Serve index.html
const indexFile = path.join(pathToBuildFolder, "index.html");
app.get('*', function (request, response) {
response.sendFile(indexFile);
});
Is this okay with you?
In this line of code, taken from code above, do we need 'join' 'or 'resolve'?
const indexFile = path.join(pathToBuildFolder, "index.html");
Sure, all that is fine. Again, the server in this gist is meant as a short example to illustrate a general point, it is not intended to catch all edge cases or be production ready. Feel free to copy it and modify it as you see fit.
Since you reference CRA, you may just want to use the example they give, which should match your setup: https://create-react-app.dev/docs/deployment/#other-solutions
Thanks for the confirmation. Yes, I can understand your example is just for illustration.
Somewhere you said, in production you should use a framework like Next.js. Are you not in favour of SPAs? I believe that the SPA technique comes really handy for building apps that are going to be used by a handful of users like Enterpise CRM, ERP, etc. What SPAs lack are SSR and SEO but there are workarounds for these two as of now. I believe that the genius would be able to overcome these two limitations completely in future.
One more question pl.
A user browses to the my-site.com
for the first time:
-
The static assets (
excluding index.html
) are served first to the browser because the Express server invokes theapp.use(express.static..)
global middleware firstbefore serving
index.html. -
Then
app.get ("*", ...)
route is hitnext
which sends the index.html to the browser. -
The browser
reads the index.html
and when it comes across the script tags that contain pointers to to the JS and CSS files, itcomes back
to the server. The server serves it using the global middleware mentioned in Step 1.
Is this how the process works? If yes, it means one unnecessary call to the server.
I think the browser must be smart enough to pick the JS and CSS assets from the user's machine itself which were served in step 1 and the step 3 won't be executed.
Your viewpoints pl.
With Regards
Somewhere you said, in production you should use a framework like Next.js. Are you not in favour of SPAs? I believe that the SPA technique comes really handy for building apps that are going to be used by a handful of users like Enterpise CRM, ERP, etc. What SPAs lack are SSR and SEO but there are workarounds for these two as of now. I believe that the genius would be able to overcome these two limitations completely in future.
I think fully client-side rendered apps have their place, but SSR frameworks are generally a better choice because they allow for more flexibility. For example, with Next.js you can do client-side rendering, server-side rendering, or static generation on a page by page basis. With CRA, you are limited to only client-side rendering. One of the biggest downsides to a fully client-side rendered app is performance, the user has to wait for ALL the JS to be downloaded, parsed, and executed before they can even see anything on the page.
Is this how the process works? If yes, it means one unnecessary call to the server.
Not quite. When a user browses to www.my-site.com
for the first time their browser makes a request for the index.html page: GET /
. The index.html is returned to the user's browser and the browser starts parsing the HTML. When it encounters <script>
or <link>
tags referring to JS or CSS assets, the browser will request those from the server: GET /bundle.js
, GET /styles.css
. That's it, no unnecessary requests. The Express routes are all middlewares, so they don't generate additional requests when they execute on a single incoming HTTP request.
I blogged about this awhile ago: http://ryanogles.by/conceptualizing-how-a-modern-single-page-app-is-served/
I blogged about this awhile ago: http://ryanogles.by/conceptualizing-how-a-modern-single-page-app-is-served/
The sequence diagram has helped me understand "clearly" how SPAs actually work and what exactly happens after the user requesting the browser to load a SPA.
You helped me quite a lot.
One more query, Hope you'd answer.
Rewrites allow you to map an incoming request path to a different destination path. Next has built-in functionality for this. But how to implement it in React SPA.. just give an idea.
Source /api/*
Destination /index.html
Effect All requests → /index.html
Thanks
Hi @Ramandhingra,
Any server-side routing is done using standard Express features. Please check the docs for Express.
All client-side routing/rewriting/redirecting is done using React Router (or whatever client-side router you are using). Please check the docs for React Router.
In the future, please direct your questions to any of the community resources available, such as StackOverflow. https://www.reactiflux.com/ is a great learning tool for React. You could join the discord and ask questions there. Good luck!
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.
Hi @ryanoglesby08
what is the folder structure that is assumed that your project has, in order to use this piece of code ?
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.)
@Ramandhingra
Based on the name of that path "/updateUserProfile" it sounds like this is an action and not a navigation, so an HTML form with an
onSubmit
handler would probably be a more appropriate and semantic HTML element to use. This also has the benefit of not causing a navigation event by default. You could then navigate the user to a new page after the fetch/axios request if desired.If you are going full client-side rendered SPA, most (likely all) actions and navigations should not cause another request to the server, since all the code is already on the client and refreshing the page would be wasteful. In the scenario you describe, I imagine you probably want to use an HTML form to trigger the network request, and React Router for any navigation.