16 | );
17 |
18 | const AppRoutes = ({ store }) => (
19 |
20 |
21 | {/* */}
22 | {
23 | if (store) {
24 | // Bad & ugly just to change the store server side through actions before rendering
25 | store.dispatch(addTodo('This should come renderer from server (on /Page direct hit)'));
26 | }
27 |
28 | return ;
29 | }} exact />
30 |
31 |
32 | )
33 |
34 | function App (props) {
35 | return (
36 |
37 | {
38 | props.location
39 | ? (
40 |
41 |
42 |
43 | ) : (
44 |
45 |
46 |
47 | )
48 | }
49 |
50 | );
51 | }
52 | export default App;
53 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
33 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/server/react-renderer.js:
--------------------------------------------------------------------------------
1 | const React = require('react')
2 | const renderToString = require('react-dom/server').renderToString;
3 | const matchPath = require('react-router').matchPath;
4 | const path = require('path');
5 | const fs = require('fs');
6 | const configureStore = require('../src/configure-store').default;
7 |
8 | const initialState = {
9 | todos: [
10 | {
11 | id: 0,
12 | text: 'Task in initialState from server',
13 | completed: false
14 | },
15 | ],
16 | };
17 |
18 | /**
19 | * Import our main App component
20 | * Remember it's exported as ES6 module, so to require it, you must call .default
21 | */
22 | const App = require('../src/App').default;
23 |
24 | exports = module.exports;
25 |
26 | exports.render = (routes) => {
27 | return (req, res, next) => {
28 |
29 | /**
30 | * Take routes collection and see if it's a valid app's route
31 | */
32 | var match = routes.find(route => matchPath(req.path, {
33 | path: route,
34 | exact: true,
35 | }));
36 |
37 | const is404 = req._possible404;
38 |
39 | if (match || is404) {
40 | /**
41 | * Point to the html file created by CRA's build tool and open it
42 | */
43 | const filePath = path.resolve(__dirname, '..', 'build', 'index.html');
44 |
45 | fs.readFile(filePath, 'utf8', (err, htmlData) => {
46 | if (err) {
47 | console.error('err', err);
48 | return res.status(404).end(); // WARNING: This 404 will be handled by Express server and won't be your React 404 component.
49 | }
50 |
51 | const location = req.url;
52 |
53 | if (is404) {
54 | /**
55 | * Set the app's response to 404 OK (https://httpstatuses.com/404)
56 | */
57 | res.writeHead(404, { 'Content-Type': 'text/html' })
58 | console.log(`SSR of unrouted path ${req.path} (404 ahead)`)
59 | }
60 | else {
61 | /**
62 | * Set the app's response to 200 OK (https://httpstatuses.com/200)
63 | */
64 | res.writeHead(200, { 'Content-Type': 'text/html' })
65 | console.log(`SSR of ${req.path}`);
66 | }
67 |
68 | const store = configureStore(initialState);
69 |
70 | /**
71 | * Convert JSX code to a HTML string that can be rendered server-side with
72 | * `renderToString` a method provided by ReactDOMServer
73 | *
74 | * This sets up the app so that calling ReactDOM.hydrate() will preserve the
75 | * rendered HTML and only attach event handlers.
76 | * (https://reactjs.org/docs/react-dom-server.html#rendertostring)
77 | */
78 | const jsx =
79 | const reactDom = renderToString(jsx);
80 |
81 | /**
82 | * inject the rendered app and it state
83 | * into our html and send it
84 | */
85 | return res.end(
86 | htmlData.replace(
87 | '',
88 | `
${reactDom}
`
89 | ).replace(
90 | '__REDUX__',
91 | JSON.stringify(store.getState())
92 | )
93 | );
94 | });
95 | }
96 | else {
97 | req._possible404 = true;
98 | return next();
99 | }
100 | };
101 | };
102 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## How to run the project
4 |
5 | Before running any script you should run:
6 |
7 | `yarn install`
8 |
9 | Or
10 |
11 | `npm install`
12 |
13 | In the project directory, you can run:
14 |
15 | ### `yarn start-server` or `npm run start-server`
16 |
17 | Runs the app in production mode (although is a PoC, we wanted to make it work as much as will do in production).
18 |
19 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
20 | You will also see requests logs in the console, using [https://github.com/dariomac/dm-logger](https://github.com/dariomac/dm-logger).
21 |
22 | If you find this repo and didn't read the full article, you can do it here: [https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020](https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020)
23 |
24 | ## Create-React-App default scripts
25 |
26 | ### `yarn start`
27 |
28 | Runs the app in the development mode.
29 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
30 |
31 | The page will reload if you make edits.
32 | You will also see any lint errors in the console.
33 |
34 | ### `yarn test`
35 |
36 | Launches the test runner in the interactive watch mode.
37 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
38 |
39 | ### `yarn build`
40 |
41 | Builds the app for production to the `build` folder.
42 | It correctly bundles React in production mode and optimizes the build for the best performance.
43 |
44 | The build is minified and the filenames include the hashes.
45 | Your app is ready to be deployed!
46 |
47 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
48 |
49 | ### `yarn eject`
50 |
51 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
52 |
53 | 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.
54 |
55 | 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.
56 |
57 | 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.
58 |
59 | ## Learn More
60 |
61 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
62 |
63 | To learn React, check out the [React documentation](https://reactjs.org/).
64 |
65 | ### Code Splitting
66 |
67 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
68 |
69 | ### Analyzing the Bundle Size
70 |
71 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
72 |
73 | ### Making a Progressive Web App
74 |
75 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
76 |
77 | ### Advanced Configuration
78 |
79 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
80 |
81 | ### Deployment
82 |
83 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
84 |
85 | ### `yarn build` fails to minify
86 |
87 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
88 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready.then(registration => {
134 | registration.unregister();
135 | });
136 | }
137 | }
138 |
--------------------------------------------------------------------------------