23 | );
24 | }
25 | }
26 |
27 | export default App;
28 |
--------------------------------------------------------------------------------
/examples/codeSplitting/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "my-ssr-example",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.6.3",
7 | "react-dom": "^16.6.3",
8 | "react-router-dom": "^4.3.1",
9 | "react-scripts": "2.1.1"
10 | },
11 | "scripts": {
12 | "start": "react-scripts-ssr start",
13 | "build": "react-scripts build",
14 | "test": "react-scripts test",
15 | "eject": "react-scripts eject",
16 | "build-server": "react-scripts-ssr build-server"
17 | },
18 | "eslintConfig": {
19 | "extends": "react-app"
20 | },
21 | "browserslist": [
22 | ">0.2%",
23 | "not dead",
24 | "not ie <= 11",
25 | "not op_mini all"
26 | ],
27 | "devDependencies": {
28 | "react-scripts-ssr": "^0.1.5"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/examples/codeSplitting/src/server.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { StaticRouter as Router } from "react-router-dom";
3 | import App from "./App";
4 | const express = require("express");
5 | const { createSSRMiddleware } = require("react-scripts-ssr");
6 | const { renderToString } = require("react-dom/server");
7 |
8 | const server = express();
9 |
10 | server.use(
11 | createSSRMiddleware((req, res, next) => {
12 | const body = renderToString(
13 |
14 |
15 |
16 | );
17 | console.log("body", body);
18 |
19 | next({ body }, req, res);
20 | })
21 | );
22 |
23 | const PORT = process.env.REACT_APP_SERVER_SIDE_RENDERING_PORT || 8888;
24 | server.listen(PORT, () => {
25 | console.log(`server running on port ${PORT}`);
26 | });
27 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-scripts-ssr",
3 | "version": "0.1.11",
4 | "repository": "https://github.com/leanjscom/react-scripts-ssr",
5 | "license": "MIT",
6 | "engines": {
7 | "node": ">=6"
8 | },
9 | "bugs": {
10 | "url": "https://github.com/leanjscom/react-scripts-ssr/issues"
11 | },
12 | "dependencies": {
13 | "babel-loader": "^8.0.4",
14 | "babel-plugin-named-asset-import": "^0.2.3",
15 | "commander": "^2.19.0",
16 | "cross-spawn": "^6.0.5",
17 | "express": "^4.16.4",
18 | "http-proxy-middleware": "^0.19.0",
19 | "node-fetch": "^2.3.0",
20 | "nodemon": "^1.18.7",
21 | "react": "^16.6.3",
22 | "react-dom": "^16.6.3",
23 | "react-scripts": "2.1.1"
24 | },
25 | "scripts": {
26 | "start": "react-scripts-ssr start",
27 | "build": "react-scripts-ssr build-server"
28 | },
29 | "bin": {
30 | "react-scripts-ssr": "./bin/react-scripts-ssr.js"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/middlewares.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const path = require("path");
3 | const proxy = require("http-proxy-middleware");
4 | const render = require("./render");
5 | const { Router } = express;
6 |
7 | function renderMiddleware(payload, req, res, next) {
8 | render(payload, req, res, next);
9 | }
10 |
11 | function createSSRMiddleware(middleware) {
12 | const router = Router();
13 | if (process.env.NODE_ENV === "production") {
14 | router.use(
15 | "/static",
16 | express.static(path.join(process.cwd(), "build/static"))
17 | );
18 | } else {
19 | router.use(
20 | ["/static", "/sockjs-node", "/api"],
21 | proxy({
22 | target: `http://localhost:${process.env.REACT_APP_DEV_SERVER_PORT}`,
23 | ws: true
24 | })
25 | );
26 | }
27 | router.use(middleware);
28 | router.use(renderMiddleware);
29 |
30 | return router;
31 | }
32 |
33 | module.exports = {
34 | createSSRMiddleware
35 | };
36 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015-present LeanJS
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/examples/codeSplitting/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component, Suspense } from "react";
2 | import { Route, Link } from "react-router-dom";
3 | import logo from "./logo.svg";
4 | import "./App.css";
5 | const LazyComponent = React.lazy(() => import("./LazyComponent"));
6 |
7 | class App extends Component {
8 | render() {
9 | return (
10 | <>
11 | (
15 |
16 |
17 |
18 |
19 | Edit src/App.js and save to reload.
20 |
21 |
22 | Get lazy>
23 |
24 |
25 |
26 | )}
27 | />
28 | (
31 | Loading...}>
32 |
33 |
34 | )}
35 | />
36 | >
37 | );
38 | }
39 | }
40 |
41 | export default App;
42 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-scripts-ssr
2 |
3 | Create React apps with server-side rendering (SSR) with no configuration
4 |
5 | # Installation
6 |
7 | `npm install react-scripts-ssr --save-dev`
8 |
9 | # Getting started
10 |
11 | ## Steps
12 |
13 | ### Step 1
14 |
15 | In the scripts section of your package.json:
16 |
17 | - Replace `"start": "react-scripts start"` with `"start": "react-scripts-ssr start",`
18 | - Add `"build-server": "react-scripts-ssr build-server",`
19 |
20 | ### Step 2
21 |
22 | - `npm install express --save`
23 | - Create the following file in src/server.js
24 |
25 | ```javascript
26 | const React = require("react");
27 | const express = require("express");
28 | const { createSSRMiddleware } = require("react-scripts-ssr");
29 | const { renderToString } = require("react-dom/server");
30 | import App from "./App";
31 |
32 | const server = express();
33 |
34 | server.use(
35 | createSSRMiddleware((req, res, next) => {
36 | const body = renderToString();
37 | next({ body }, req, res);
38 | })
39 | );
40 |
41 | const PORT = process.env.REACT_APP_SERVER_SIDE_RENDERING_PORT || 8888;
42 | server.listen(PORT, () => {
43 | console.log(`server running on port ${PORT}`);
44 | });
45 | ```
46 |
47 | You can edit the server.js file with your custom code and other middlewares.
48 |
49 | ### Step 3
50 |
51 | `npm start`
52 |
53 | ## Caveats
54 |
55 | It only works with Create React App version 2
56 |
--------------------------------------------------------------------------------
/bin/react-scripts-ssr.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | var spawn = require("cross-spawn");
3 | const args = process.argv.slice(2);
4 |
5 | const scriptIndex = args.findIndex(x => x === "build-server" || x === "start");
6 | const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
7 | const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];
8 |
9 | switch (script) {
10 | case "proxy":
11 | case "build-server":
12 | case "start": {
13 | const result = spawn.sync(
14 | "node",
15 | nodeArgs
16 | .concat(require.resolve("../scripts/" + script))
17 | .concat(args.slice(scriptIndex + 1)),
18 | { stdio: "inherit" }
19 | );
20 | if (result.signal) {
21 | if (result.signal === "SIGKILL") {
22 | console.log(
23 | "The build failed because the process exited too early. " +
24 | "This probably means the system ran out of memory or someone called " +
25 | "`kill -9` on the process."
26 | );
27 | } else if (result.signal === "SIGTERM") {
28 | console.log(
29 | "The build failed because the process exited too early. " +
30 | "Someone might have called `kill` or `killall`, or the system could " +
31 | "be shutting down."
32 | );
33 | }
34 | process.exit(1);
35 | }
36 | process.exit(result.status);
37 | break;
38 | }
39 | default:
40 | console.log('Unknown script "' + script + '".');
41 | console.log("Perhaps you need to update react-scripts?");
42 | console.log(
43 | "See: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#updating-to-new-releases"
44 | );
45 | break;
46 | }
47 |
--------------------------------------------------------------------------------
/examples/codeSplitting/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/examples/helloWorld/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/examples/helloWorld/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
--------------------------------------------------------------------------------
/examples/codeSplitting/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
35 |
36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
37 |
38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
--------------------------------------------------------------------------------
/src/render.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 | const fs = require("fs");
3 |
4 | const injectHTML = (
5 | page,
6 | { html = "", title = "", meta = [], body = "", scripts = [], state } = {}
7 | ) => {
8 | let responsePage = page.replace("", ``);
9 | responsePage = responsePage.replace(/