How to use ReactDOMServer.renderToStaticMarkup without nodejs server - node.js

I want to use ReactDOMServer.renderToStaticMarkup to create a static website, but I only want to generate the html string once during build instead of dynamically for every request
Here are the relevant docs, but they don't go into much detail on implementation https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
What is the best practice for using react to generate html one time during build instead of dynamically on every page request? I am using webpack.

For anyone who comes here looking for answers, here's how I did it:
Create a separate webpack config file for your SSR react like webpack.ssr.js. This file will have the same config you'd normally have for react SSR.
In the index.js file where you'd usually have ReactDOM.render, run the ReactDOMServer.renderToStaticMarkup function.
In the index.js file, write the html string to a file:
const html = ReactDOMServer.renderToStaticMarkup(App);
fs.writeFile("index.html", html, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
}
});
After every build, execute the build file as a node script. For example node build.js. I'd recommend doing this in package.json as a postbuild script. For example:
postbuild: "node build.js"
The fs.writeFile will update the index.html file each time you build, so you'll just need to serve index.html like you would with any other static website.
For css modules, you'd use something like isomorphic-style-loader instead of the regular style-loader.
If you are using something like react-router, you'll need to iterate through all your routes and run ReactDOMServer.renderToStaticMarkup and fs.writeFile for every route. Then you'd serve the different html files with server side routing.
This will also work for normal SSR using ReactDOMServer.renderToString, especially if you don't need dynamic SSR based on something like an ID. For generating the loading screen server side, this is great and there's really no reason to generate html dynamically at runtime.

Related

Deploy production build of ReactJS with Node express as backend

Hi even after lot of search i am still confused what is correct way to deploy my react app created using create-react-app with express as backend.
I ran npm run build which created build folder. I copied the build folder to be served as static folder of express and had put
app.use(express.static('build'));.
It is working fine for homepage, that is homepage opens when i run my express node server but when i go to anyother link outside homepage it gives 404.
Everything is working fine in developer mode, which i run by npm start command. I just want to know what i am doing wrond here. Let me know anymore info required to understand the problem. Thankyou.
It sounds like you don't have the backend server running. You need to npm start your server, and then npm start your front end if that make sense. They are 2 separate things.
Are you using client-side routing? A popular implementation of that is react-router.
Let say you are trying to access /page1, what client-side routing does is use the JS to toggle between different components to "fake" the routing, instead of rending a new HTML.
Yet, by default when you change routes, the browser does the usual stuff and send a GET request to the server asking for the corresponding HTML file. But since you only have index.html served, that's why you received 404.
You need to add the following at the end of your app.js, right before you call app.listen of your express server to tell the server to always return index.html no matter what route does it received.
/* client-side routing.
* For GET requests from any routes (other than those which is specified above),
* send the file "index.html" to the client-side from the folder "build"
*/
app.get("*", (_, res) => res.sendFile("index.html", { root: "build" }));
// your usual app.listen
app.listen(port, () => console.log("Listening"));

Hide preloaded state in .js file?

When I do SSR in my React apps (using Node.js / Express), and using Redux for state, I always end up with a similar to window.__PRELOADED_STATE__ = {....}
This output is something rendered together with the generated html code from renderToString but I'm wondering if there is a way to get that preloaded state variable inside a "virtual" js file instead (that can be referenced in my main layout template file), just to make the source code cleaner, without having to do the same rendering process twice?
I currently do my SSR via a middleware that I've setup in my Node.js/Express app.
Anyone has any ideas or recommendations?
Thanks

How to send server-side variables to vue instance using webpack & vue-cli?

I am currently making a project using vue-cli which generates a Node project with webpack. I can build all scripts and use the pug language within .vue files. When building, the project uses HTML-Webpack-Plugin, though, which outputs the code as static HTML with client-side scripts.
How do I pass variables from the server-side to these client-side scripts? I previously was using pug, which made this process easy, but since it now gets built into .html files, this can no longer be done.
I have two attempts, both suboptimal:
1. Send variables into clientside scripts
script.
const clinetSideVar = `!{serverSideVar}`;
The problem with this approach is that I cannot pass this variable into the vue instance, since it gets obfuscated when built and I have no way of accessing it (or do I? I haven't found a way).
2. Using AJAX requests
I could also make a restful API for server-side site data and retrieve it using AJAX, but this seems like a real hack and this would lose quite a bit of performance over just sending the data plainly through a pug template (with no. 1 I'd too, since client-side JS would have to insert the data into the DOM).
I'd recommend using JSONP (since your index.html is built ahead of time in Vue-cli).
In your public/index.html (which is a template)
<head>
...
<script>function getServerData(data) { window.__SERVER_DATA__ = data; }</script>
<script src="/api/server-data.json?callback=getServerData"></script>
</head>
In your Node Express routes definition
const app = express();
// ...
app.get('/api/server-data.json', (req, res) => {
res.jsonp({
foo: 'foo',
bar: 'bar'
});
});
Then just access window.__SERVER_DATA__ from within any Vue component.

Use javaScript file in angular 5 project

I am building a web application using Angular 5 and nodejs with express. As both the frontend and the backend are going to run in the same server I want to use my backend javascript functions in the frontend. The solutions that I have found didn't worked for me.
appController.js
var createApp = function (appData) {
console.log("App created")
}
exports.createApp = createApp;
This is the backend file that I want to use in the front.
Javascript files don't need to export things when used in the front-end. Most of the time, they use global variables. You should go with that.
To add it to your project, add it anywhere you want, and in your Typescript, you can simply use
declare var myGlobalVariable: any;
// ...
myGlobalVariable.createApp();
I did a similar thing. I have a frontend with Angular 5 and a backend serving an API via Express:
If you want to run your Angular frontend and your NodeJS backend on the same server you'll have to build your Angular project and serve the built files with your Express server.
I think I found a tutorial on that – but I can't find it right now...
Instead maybe have a look at my code for the backend:
https://github.com/saitho/ngHashi/blob/next/backend/src/index.ts
In production mode it will serve the files in the folder /backend/dist_frontend by default (apart from the backend routes (/api)). I use a build process (GitLab CI) to move the files I need to the respective place...
I finally find a solution. It would be necessary to modify the tsconfig.json:
tsconfig.json
{
compilerOptions: {
.....
allowJS: true,
......
}
}

Can I use webpack on the client side without nodejs server?

I am trying to build a web app where I want to store all html, js and css files on amazon s3, and communicate with a restful server through api.
I am trying to achieve lazy loading and maybe routing with react router. It seems that webpack has this feature code splitting that would work similarly as lazy loading.
However, all of the tutorial and examples I found involves webpack-dev-server, which is a small node express server. Is there anyway I could generate bundle at build time and upload everything to amazon s3 and achieve something similar to Angular's ocLazyLoading?
It's definitely possible to create a static bundle js file, which you can use in your production code that does not include webpack-dev-server.
See this example as a reference (note: I am the owner of this repo). webpack.prod.config.js does create a production ready bundle file using webpack via node.js which itself does not require node.js anymore. Because of that you can simply serve it as a simple static file (which is done in the live example).
The key difference is how the entry points are written in the dev- and production environments. For development webpack-dev-server is being used
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
// ...
}
In the production environment you skip the webpack-dev-server and the hot reloading part
module.exports = {
entry: [
'./src/index'
],
// ...
}
If you want to split your code into more than one bundle, you might want to have a look at how to define multiple entry points and link the files accordingly.

Resources