Giter Club home page Giter Club logo

template-react-ssr's Introduction

React SSR Template

This project provides a template for React 16 (Fiber) using server side rendering.

Important: The master branch is only supposed to contain the bare-bone template. There are different branches containing more advanced features, like streaming and more to come in the future. Those are documented in the Branches section.

The template has been renamed to template-react-ssr since it will upgrade to newer versions of React, as soon as they are stable.

Table of contents

Features

  • Universal rendering using ExpressJS and EJS
  • Hot reloading of styles and scripts
  • ESNext ready
  • powered by webpack

Branches

The following, more advanced, features are pushed to dedicated branches. Either checkout a specific branch or fork the repository and merge the branches to get the features you need. You might as well just use them as a resource to learn, how the specific technologies are implemented.

Streaming (feature/streaming)

Since React 16, we have the possibility to render to a node stream. This improves the time to first byte (TTBF), since the browser can display the app in an iterative manner. The dedicated branch provides the basic streaming implementation.

React-Router Integration (feature/react-router)

For a template using react-router you can make use of this branch. It features routing on client and server side as well as basic routes.

Thanks to @crabbits for contributing this example.

Express Routing / API (feature/express-routing)

This example shows how to configure routing ExpressJS. This can be used to create an API to work alongside your frontend application.

Redux (feature/redux)

This example shows how to integrate redux along with server-side rendering as well as hot-reloading. It features a simple store with preloaded state from the server as well as state hydration on the client.

Development

To start development, follow these steps:

$ git clone https://github.com/rherwig/template-react-ssr.git
$ cd template-react-ssr
$ npm i
$ npm start

This fires up the development server on port 3000.

You can now choose to either start developing your react application or to enhance the express server according to your needs.

The react app's entry point is src/shared/App.js and the express server is started from src/index.js.

For more information on how the specific parts of the application work, please refer to the documentation in the code.

Testing

The general testing engine used by this project consists of jest and react-test-renderer. You can run the tests by using the following command:

$ npm test

Linting

To run eslint, execute the following command:

$ npm run lint

Please note: Linting is only available via this command and not integrated via webpack. This is done on purpose, as eslint is somewhat biased on the preference of the creator of the config.

Building for Production

In order to build for production and run the finished project, execute the following:

$ npm run build
$ node public/index

This bundles and optimizes your app and runs it from the public/ directory.

Debugging

This section explains how to debug server and client side of the app in various IDEs.

VSCode

In order to debug with VSCode, you want to create a debug configuration. This is configured via the launch.json file located inside the .vscode directory of your project.

Use the following launch.json for debugging:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/src/index.js",
            "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
            "runtimeArgs": ["--nolazy"],
            "env": {
                "NODE_ENV": "development"
            }
        }        
    ]
}

After setting up the configuration, start debugging by either selecting Debug > Start Debugging in the main menu bar or by pressing F5 on your keyboard.

Changelog

For a detailed changelog, please refer to the CHANGELOG.md.

Planned features

The following features are planned for future upgrades of the template. If there are any request, feel free to open an issue or a pull request.

  • Provide service worker template branch
  • Provide fully features PWA example in a separate repository
  • Extend this list ;-)

License

MIT

Contributing

If there are any ideas or optimizations to improve this template, feel free to submit a pull request including your documented changes.

template-react-ssr's People

Contributors

crabbits avatar dependabot[bot] avatar rherwig avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

template-react-ssr's Issues

utils.js:50 chunk not available for synchronous require yet:

getting the following error utils.js:50 chunk not available for synchronous require yet: for my multiple modules, could you please describe what could be the issue and how can i control my chunks size

Sample error

utils.js:50 chunk not available for synchronous require yet: ./src/shared/components/AhHeader.js: Module build failed (from ./node_modules/extract-css-chunks-webpack-plugin/dist/loader.js):
ModuleParseError: Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.

(Source code omitted for this binary file)
    at handleParseError (/mnt/www/artifacts/x/5820/node_modules/webpack/lib/NormalModule.js:432:19)
    at doBuild.err (/mnt/www/artifacts/x.dev/5820/node_modules/webpack/lib/NormalModule.js:466:5)
    at runLoaders (/mnt/www/artifacts/x.dev/5820/node_modules/webpack/lib/NormalModule.js:327:12)
    at /mnt/www/artifacts/x.dev/5820/node_modules/loader-runner/lib/LoaderRunner.js:370:3
    at iterateNormalLoaders (/mnt/www/artifacts/x.dev/5820/node_modules/loader-runner/lib/LoaderRunner.js:211:10)
    at Array.<anonymous> (/mnt/www/artifacts/x.dev/5820/node_modules/loader-runner/lib/LoaderRunner.js:202:4)
    at Storage.finished (/mnt/www/artifacts/x.dev/5820/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:43:16)
    at provider (/mnt/www/artifacts/x.dev/5820/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:79:9)
    at /mnt/www/artifacts/x.dev/5820/node_modules/graceful-fs/graceful-fs.js:78:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3) Error: Module build failed (from ./node_modules/extract-css-chunks-webpack-plugin/dist/loader.js):
ModuleParseError: Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)

separate fonts from style

currently in my style file i am calling a custom font like

@font-face {
  font-family: "MetricMedium";
  src: url("../fonts/MetricMedium.ttf");
}

i am planning to separate style and font and load on the page separately.
currently doing like this:

const chunkNames = flushChunkNames();
const { js, styles, cssHash } = flushChunks(clientStats, { chunkNames });

i was wondering if there is a way i can get fonts also so i can load it separately
const { js, styles, cssHash, fonts } = flushChunks(clientStats, { chunkNames });

Am I right in understanding that the feature branches are now behind the master branch?

I'm basically trying to get this to work with Redux and React-Router.

Am I right in that there have been changes (mostly - switching to Helmet) - that have made Master 3.0.0 incompatible (or at least requiring updating/merging resolution) with the feature branches?

In anycase - here's my attempt to catch feature/redux up with master:

https://github.com/dwjohnston/template-react-ssr/tree/feature/redux-catchup

Static cache

I am using this template and in top of this i have modified it to support static(browser) cache
for 30 days and based on that after every build i am generating new has([contenthash]) for my all js file

sample code format

 output: {
        filename: 'app.client.js',
        chunkFilename: '[name].[contenthash].js'
    },

i Needed some help to understand the generation and use of app.client.js and is there a way i can add [contenthash] to app.client.js file also and where exactly this file is referred to.
https://github.com/rherwig/template-react-ssr/blob/master/webpack/client/common.js#L9

Repository structure

Hey guys!

I'm currently thinking about the repository structure. At the moment, the master features only the most basic boilerplate, to avoid libs and clutter that are not needed for some people.

The different extensions like routing, streaming and so on reside in dedicated feature branches.

I am not sure, if I like this approach.

On the one hand, I want to provide a very basic template that you don't need to delete half of the packages from when working with it and that illustrates the basic SSR workflow. On the other hand, I want to provide a full jump-start-boilerplate for PWA at some point soon.

The full example could go into master and the feature branches could hold the basic example and extended examples or the approach like it is now continues.

I need your feedback :-)

Throwing error while deploying in firebase-functions

I am trying to deploy my SSR app in firebase originally forked from this repo, after doing some modification in the app. Which works fine when I do sudo firebase serve --only functions,hosting but throwing error when I do firebase deploy. The reproducible repo is https://github.com/subhendukundu/template-react-ssr/tree/feature/react-router, which has a package.json https://github.com/subhendukundu/template-react-ssr/tree/feature/react-router/public I am using the public directory as my function directory as well, https://github.com/subhendukundu/template-react-ssr/blob/feature/react-router/firebase.json

However even if I am using a different function directory for my cloud functions I see the same errors. Is there anyway I can fix it?
Error message:

Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: TypeError: react_universal_component__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function
    at Object.<anonymous> (/user_code/assets/app.server.js:1525:128)
    at Object.module.exports.hasOwnProperty (/user_code/assets/app.server.js:1547:30)
    at __webpack_require__ (/user_code/assets/app.server.js:27:30)
    at Object.<anonymous> (/user_code/assets/app.server.js:13330:26)
    at __webpack_require__ (/user_code/assets/app.server.js:27:30)
    at Object.<anonymous> (/user_code/assets/app.server.js:8001:18)
    at __webpack_require__ (/user_code/assets/app.server.js:27:30)
    at /user_code/assets/app.server.js:104:18
    at Object.<anonymous> (/user_code/assets/app.server.js:107:10)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)

Please note that the original error massage was TypeError: c(...) is not a function at Object.. I have turned off the minifiation to see the error message at the moment, still confused what's going wrong.

PSA: Scaffolding universal react apps based on this template

Hey there,

since I updated this template quite a lot, I more and more think that the feature branch approach, as it is practiced right now, makes the template more and more difficult to maintain and keep every branch up to date.

I came up with a solution and would be grateful to receive some feedback.

The idea is to build a project scaffolding CLI that generates universal react apps based on this template. In the course of scaffolding, you get to choose which of the features from the dedicated branches you need (streaming, react-router, redux, ...). What comes out is a ready-to-go boilerplate that fits your needs.

The project is called rusc ("React Universal Scaffolding CLI") and is currently in development.

https://github.com/rherwig/rusc

As of now, the base template can already be scaffolded and the mechanics to use the various feature is in place.

where does universal get its path from

In your UniversalComponent, your component looks like this:

import universal from 'react-universal-component';

export default universal(({ name }) => import(`./${name}`));

How is the path ./${name}/ resolving? Is the cwd() not the root of the site?

I am confused as to how this is working.

svg jpg file load

Hi @rherwig i have few question, i am new to webpack

  1. I am trying to import svg, jpg file but i get the error
    Module parse failed: Unexpected token (1:0)
    You may need an appropriate loader to handle this file type.

    If you have any example to add loaded for these files

  2. what is the use of this https://github.com/rherwig/template-react-16-ssr/blob/feature/react-router/webpack/client.js#L39 why are we including bootstrap,
    as i see bootstrap.js is added in my DOM, is there a way i can remove it(should i remove it)

Server side only routes/components?

I'm just getting started with this template - and am checking out the react-router feature branch.

What I'm wondering with it - say I have some pages that are static, and are intended for indexing - 'About Us', 'Blog' etc.

If I set that all up in the shared folder like you have done - and I navigate directly to the page then it renders on the serverside.

However, I am at home first, and then I clicked a link to navigate to /About then the rendering happens on the client side.

I'm just wondering about this unnecessarily increases the bundle size. ie. What if these static pages contain thousands of words.

Is this a worthwhile concern, or should code splitting solve this anyway?

node-gyp/iltorb installation issue (with solution)

If I do a fresh clone, I get this issue:

sed: can't read ./Release/.deps/Release/obj.target/zopfli/src/png/zopflipng.o.d.raw: No such file or directory
rm: cannot remove './Release/.deps/Release/obj.target/zopfli/src/png/zopflipng.o.d.raw': No such file or directory
zopfli.target.mk:133: recipe for target 'Release/obj.target/zopfli/src/png/zopflipng.o' failed


npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

If you then then do

cd node_modules/node-gyp && npm i

Then try on root npm i && npm start

Error: Cannot find module './build/bindings/iltorb.node'

Now do

cd node_modules/iltorb && npm i

then npm i && npm start on the root, and it should start.

Production mode Error: You should not use <Switch> outside a <Router>

Project runs find in development mode but in but is not is production. it showing
You should not use Switch outside a Router
and when i use BrowserRouter in App.js it showing error Browser history need dom
also i try Router from react-router dom than show no error but rendring same page
kindly help me. thanks in advance

Debug server side

Hi!

Cool project. I have a question, what config do you have, if you use vscode, to debug the server side?

Thanks!

Render client side only?

I'm doing some stuff with websockets, and what I'm doing is that when a component mounts, it sets up all the websocket stuff.

I'm having an issue where the server side render of that component screws up the websocket logic. Is it possible to tell a component to render on the client side only?

Should we use eslint?

Hey everyone,

I've been thinking about implementing eslint for this project, but am not exactly sure, if this is a good idea... code-style is to a certain degree a matter of commitment in a team after all. So I don't know, if it would be wise to provide an opinion on code style via eslint.

What do you think? Eslint - yes/no? Via webpack-loader or just the config and an npm lint task for those who'd like to use it?

Out of memory error in development.

I'm getting this error every hour or so in development:

--- Last few GCs --->

[8813:0x308ad10] 10816736 ms: Mark-sweep 1384.2 (1411.6) -> 1383.2 (1412.1) MB, 606.2 / 0.1 ms  (average mu = 0.117, current mu = 0.071) allocation failure scavenge might not succeed
[8813:0x308ad10] 10817262 ms: Mark-sweep 1384.2 (1412.1) -> 1362.1 (1412.1) MB, 515.9 / 0.1 ms  (average mu = 0.075, current mu = 0.020) allocation failure scavenge might not succeed


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x872444041bd]
    1: StubFrame [pc: 0x87244407de1]
Security context: 0x25783b39e789 <JSObject>
    2: SourceMapGenerator_serializeMappings [0x16c5561dbc79] [/home/davidj/git-workspace/geoplanets/node_modules/webpack-sources/node_modules/source-map/lib/source-map-generator.js:~312] [pc=0x87248097408](this=0x3519ec69c11 <SourceMapGenerator map = 0x2c9a14f3a961>)
    3: SourceMapGenerator_toJSON [0x16c5561dbcf9] [/home...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x8b8210 node::Abort() [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 2: 0x8b825c  [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 3: 0xac1d1e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 4: 0xac1f38 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 5: 0xeb11f2  [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 6: 0xebd14a v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 7: 0xebdab4 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 8: 0xec03e5 v8::internal::Heap::AllocateRawWithRetry(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
 9: 0xe888c4 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
10: 0x112a2ae v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/home/davidj/.nvm/versions/node/v10.8.0/bin/node]
11: 0x872444041bd 

It's not a huge problem as I can just start the dev server again. Still - are you encountering this?

Implement testing foundation

Since testing is obviously a thing in development ;-) the idea to implement a foundation for writing tests into the template (containing tests for the existing boilerplate components).

This probably is achieved with jest and enzyme.

configureProduction errors trying to require files that do not exist

In src/index you have this code:

const configureProduction = app => {
    const clientStats = require('./assets/stats.json');
    const serverRender = require('./assets/app.server.js').default;
    const publicPath = '/';
    const outputPath = join(__dirname, 'assets');

    app.use(publicPath, express.static(outputPath));
    app.use(serverRender({
        clientStats,
        outputPath
    }));

    app.set('views', join(__dirname, 'views'));
};

If I am running in development or these files do not exist then I get Can't resolve xxxx errors.

Am I missing something or how can this work?

Thanks for this project, I've found it very useful.

add styles to template

just wanted to know how can i add .css(styl) file directly to .ejs,
i tried adding it to ejs by keeping my file is public directory but say file not found, so what is the best way to add some style globally?

Can you add README file for this project?

Hi @rherwig,

I really liked your implementation of react-16's server-side rendering. I like to understand this example better, so would need some assistance in understanding the code. As I am also planning to create react app with will have ssr feature, which will have backend express app which will call some third party api and render the response to react components.

Thanks!!

EJS rendering for SEO

Hi,
i am trying to render my component on server, a component which fetches the data from another 3rd party API on componentDidMount, my component is rendering fine but when is pass the string returned from ReactDOM.renderToString to my .ejs file which is missing the data returned from 3rd party API

import React from 'react';
import ReactDOM from 'react-dom/server';
import { flushChunkNames } from 'react-universal-component/server';
import flushChunks from 'webpack-flush-chunks';

import App from '../shared/App';
import HorizontalModule from '../shared/Horizontal-module';
export default ({ clientStats }) => async (req, res) => {
    const app = (
        <App/>
    );
 
    const appString = ReactDOM.renderToString(app);
    const chunkNames = flushChunkNames();
    const { js, styles, cssHash } = flushChunks(clientStats, { chunkNames });
    res.render('index', {
        appString,
        js,
        styles,
        cssHash
    });

    console.log(appString);
};

my component is rendering fine, but when is see the view-source of a page component is empty.
appString is basically empty

this is where my component rendered http://ec2-13-232-170-86.ap-south-1.compute.amazonaws.com:3000/

and this is my code base https://github.com/sharmam1/testproj

deploy to heroku

hello, i'm new to react ssr. i would like to deploy to heroku, but it's failed and in heroku logs --tail gave me this:

2023-01-03T14:13:26.737554+00:00 app[web.1]: 
2023-01-03T14:13:26.737573+00:00 app[web.1]: > [email protected] start
2023-01-03T14:13:26.737579+00:00 app[web.1]: > cross-env NODE_ENV=development babel-node src/index
2023-01-03T14:13:26.737579+00:00 app[web.1]: 
2023-01-03T14:13:26.744087+00:00 app[web.1]: sh: 1: cross-env: not found
2023-01-03T14:13:27.018514+00:00 heroku[web.1]: Process exited with status 127
2023-01-03T14:13:27.068940+00:00 heroku[web.1]: State changed from starting to crashed

here my currect code
https://github.com/nashihu/react-ssr-byi

thank you in advance

How does this compare to nextjs?

NextJs is an out of the box SSR solution - supports code splitting, export to static website etc.

How does this compare? Is there something that this is doing that nextjs doesn't?

I haven't used NextJS - and for the most part, I've found this to a be a pretty clean and tidy solution.

code splitting ?

Hey thank you for this awesome template but is there any reason you aren't implementing the code splitting with react-universal-component or am i missing something. The code snipet below throws an error saying
[FLUSH CHUNKS]: Unable to find default in Webpack chunks. Please check usage of Babel plugin.

import Login from "../shared/pages/auth/login"
import Container from "../shared/components/container"

const UniversalComponent = universal((props) => import(`../shared/pages/auth/login.js`))

const routes = () => {
    return (
        <Switch>
            <Container>
                <Route path="/" component={UniversalComponent} />
            </Container>
        </Switch>
    )
}

Server side rendering with Browser API code

Just want to open a discussion on how we can achieve a Server side rendering of an App with having some window API like localstorage or Cookies

I am rendering App component at server and rendering few other component from App component some of my child component contains Cookies and Localstorage API to store the data, but when i run the App it show window not defined on Server side as window is not available at that time, what is the best way to achieve this and store some values in Client's browser.

Typescript?

This would be a pretty good candidate for typescript.

But then, it would also be less usable for people not using typescript.

Have you thought about including it?

Real-World example: What do you need?

Hey everyone,

since we plan on creating a real-world example for a PWA using this React 16, it would be great to know, what features you desire in a real-world example. Please suggest features here.

The first ones I can think of are:

  • All features of the regular master (SSR, webpack, ESNext)
  • API and react-router along with some mock requests
  • PWA features like app manifest and service worker
  • Maybe a self signed certificate with HTTP2?

npm run build not starting server

Hey there,
I am not sure, if I am the only one facing this issue. Just cloned the repo, and tried npm run build. It's building it but not starting the server.
Not getting any error either. Any help?
screen shot 2019-01-19 at 11 55 05 am
Thanks in advance.

curious to know why the webpack optimization has not been used

This project has been a great help to me to get up to speed with react ssr so many thanks for that.

I've recently upgraded to webpack 4 and the latest extract-css-chunks-webpack-plugin.

In the README for extract-css-chunks-webpack-plugin, it states that you should the webpack optimization config as a replacement for the now gone CommonsChunkPlugin.

e.g.

optimization: {
      runtimeChunk: {
        name: 'bootstrap'
      },
      splitChunks: {
        chunks: 'initial', // <-- The key to this
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendor'
          }
        }
      }
    };

I'm curious to know if there is a reason why you are not using this?

Is not needed in this case?

How does this work with express routing?

This is a really nice example. I'm a little confused where express routing would live though. Webpack seems to be doing quite a lot of stuff in the middle—between /src/index.js and /src/server/index.js. I can't seem to figure out how to access the Express app variable that's defined in src/index.js in any other files.

What would be the best practices to adding express level routing to this project?

passing props from server to client.

How do i pass my api data from server to client as props and,
is it advisable to pass API fetch data from server to client and re-use it to render component.
Note: not using redux

getting fav.ico and socket.io updates to the react-hot-server-middleware

I have been logging the calls received in the server-hot-middleware function here

I am getting fav.ico and socket.io requrests coming in here as well:

My function looks like this:

export default ({ clientStats }: { clientStats: any }) => async (req: Request, res: Response, next: any) => {
  const preloadedState: any = {};

  console.log('-----------------------');
  console.log(req.url);
  console.log('-----------------------');

  // TODO: find a better way of filtering websocket hot <reloading></reloading>
  if (some(['sockjs', 'hot-update.json', 'favicon.ico'], part => req.url.indexOf(part) > -1)) {
    next();
    return;
  }

  const store = configureStore({ router: { location: req.url} }, createMemoryHistory());

  const context: any = { store };

  store.dispatch(push(req.url));

  const app = (
    <Provider store={store}>
      <StaticRouter location={req.url} context={context}>
        <Application />
      </StaticRouter>
    </Provider>
  );

  const { js, styles } = flushChunks(clientStats, {
    chunkNames: flushChunkNames()
  });

  const appString = renderToString(app);
  const { title } = Helmet.renderStatic();

  console.dir(store.getState());

  res.status(200).send(`
    <!doctype html>
    <html lang="en">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        ${styles}
        ${title}
      </head>
      <body>
        <div id="root">${appString}</div>
        <script>
          window.__PRELOADED_STATE__ = ${serialize(preloadedState)}
        </script>
        ${js}
      </body>
    </html>
`);
};

Is this normal? Should these not be filtered out?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.