• Stars
    star
    251
  • Rank 161,862 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React SSR as a view template engine

Overview

  • SSR (Server Side Rendering) as a view template engine
  • Dynamic props
    • Passing the server data to the React client props
    • Suitable for:
      • Admin Panels
      • Blogging
  • Developer Experience
    • Zero config of webpack and babel
    • HMR (Hot Module Replacement) both scripts and even if styles when process.env.NODE_ENV !== 'production'
    • Built-in Sass (SCSS) support

Pros and Cons

Pros

Because it is just a view template engine:

  • It doesn't need to have any APIs, all we have to do is to pass the server data to the client
  • It supports multiple engines like .hbs, .ejs and React .(ts|js)x
  • We can use passport authentication as it always is

Cons

  • It is not so performant, because it assembles the whole HTML on each request
  • It does not support client side routing

Usage

With @react-ssr/express

Install it:

$ npm install --save @react-ssr/core @react-ssr/express express react react-dom

And add a script to your package.json like this:

{
  "scripts": {
    "start": "node server.js"
  }
}

Then, populate files below inside your project:

server.js:

const express = require('express');
const register = require('@react-ssr/express/register');

const app = express();

(async () => {
  // register `.jsx` or `.tsx` as a view template engine
  await register(app);

  app.get('/', (req, res) => {
    const message = 'Hello World!';
    res.render('index', { message });
  });

  app.listen(3000, () => {
    console.log('> Ready on http://localhost:3000');
  });
})();

views/index.jsx:

export default function Index({ message }) {
  return <p>{message}</p>;
}

Finally, just run npm start and go to http://localhost:3000, and you'll see Hello World!.

With @react-ssr/nestjs-express

Install it:

# install NestJS dependencies
$ npm install --save @nestjs/core @nestjs/common @nestjs/platform-express reflect-metadata rxjs

# install @react-ssr/nestjs-express
$ npm install --save @react-ssr/core @react-ssr/nestjs-express react react-dom

And add a script to your package.json like this:

{
  "scripts": {
    "start": "ts-node --project tsconfig.server.json server/main.ts"
  }
}

Then, populate files below inside your project:

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "preserve",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "strict": true,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules",
    "ssr.config.js",
    "dist",
    ".ssr"
  ]
}

tsconfig.server.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist"
  },
  "include": [
    "server"
  ]
}

server/main.ts:

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import register from '@react-ssr/nestjs-express/register';
import { AppModule } from './app.module';

(async () => {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // register `.tsx` as a view template engine
  await register(app);

  app.listen(3000, async () => {
    console.log(`> Ready on http://localhost:3000`);
  });
})();

server/app.module.ts:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';

@Module({
  controllers: [
    AppController,
  ],
})
export class AppModule {}

server/app.controller.ts:

import {
  Controller,
  Get,
  Render,
} from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index') // this will render `views/index.tsx`
  public showHome() {
    const user = { name: 'NestJS' };
    return { user };
  }
}

views/index.tsx:

interface IndexProps {
  user: any;
}

const Index = ({ user }: IndexProps) => {
  return <p>Hello {user.name}!</p>;
};

export default Index;

Finally, just run npm start and go to http://localhost:3000, and you'll see Hello NestJS!.

Configuration (ssr.config.js)

Here is the default ssr.config.js, which is used by react-ssr when there are no valid values:

module.exports = {
  id: 'default',
  distDir: '.ssr',
  viewsDir: 'views',
  staticViews: [],
  webpack: (config /* webpack.Configuration */, env /* 'development' | 'production' */) => {
    return config;
  },
};

ssr.config.js#id

The id of UI framework. (default: default)

It can be ignored only when the project does not use any UI frameworks.

Supported UI frameworks are:

For example, if we want to use emotion, ssr.config.js is like this:

module.exports = {
  id: 'emotion',
};

ssr.config.js#distDir

The place where react-ssr generates production results. (default: .ssr)

If we use TypeScript or any other library which must be compiled, the config below may be useful:

module.exports = {
  // dist folder should be ignored by `.gitignore`
  distDir: 'dist/.ssr',
};

ssr.config.js#viewsDir

The place where we put views. (default: views)

A function res.render('xxx') will render views/xxx.jsx or views/xxx.tsx.

A working example is here: examples/basic-custom-views

ssr.config.js#staticViews

If specified, react-ssr generates html cache when production:

module.exports = {
  staticViews: [
    'auth/login',
    'auth/register',
    'about',
  ],
};

ssr.config.js#webpack()

module.exports = {
  webpack: (config /* webpack.Configuration */, env /* 'development' | 'production' */) => {
    // we can override default webpack config here
    return config;
  },
};

Custom process.env.NODE_ENV

If you set process.env.REACT_SSR_ENV, you can separate process.env.NODE_ENV from react-ssr:

package.json

{
  "scripts": {
    "start": "cross-env NODE_ENV=k8s REACT_SSR_ENV=production node dist/main.js"
  }
}

Custom Babel Config

We can extends its default .babelrc like this:

.babelrc:

{
  "presets": [
    "@react-ssr/express/babel"
  ]
}

A working example is here: examples/basic-custom-babelrc

Custom App

Just put _app.jsx or _app.tsx into the views root:

views/_app.jsx:

// we can import global styles or use theming
import '../styles/global.scss';

const App = (props) => {
  // yes, this `props` contains data passed from the server
  // and also we can inject additional data into pages
  const { children, ...rest } = props;

  // we can wrap this PageComponent for persisting layout between page changes
  const PageComponent = children;

  return <PageComponent {...rest} />;
};

export default App;

A working example is here:

Custom Document

Just put _document.jsx or _document.tsx into the views root:

views/_document.jsx:

import React from 'react';
import {
  Document,
  Head,
  Main,
} from '@react-ssr/express';

export default class extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <title>Default Title</title>
          <meta charSet="utf-8" />
          <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
          <link rel="shortcut icon" href="/favicon.ico" />
        </Head>
        <body>
          <Main />
        </body>
      </html>
    );
  }
}

Note:

  • Please put <Main /> component directly under <body> tag and don't wrap <Main /> component with another components, because this is a hydration target for the client.

And then, use it as always:

views/index.jsx:

const Index = (props) => {
  return <p>Hello World!</p>;
};

export default Index;

A working example is here: examples/basic-custom-document

Dynamic Head

We can use the Head component in any pages:

views/index.jsx:

import React from 'react';
import { Head } from '@react-ssr/express';

const Index = (props) => {
  return (
    <React.Fragment>
      <Head>
        <title>Dynamic Title</title>
        <meta name="description" content="Dynamic Description" />
      </Head>
      <p>Of course, SSR Ready!</p>
    </React.Fragment>
  );
};

export default Index;

A working example is here: examples/basic-dynamic-head

Supported UI Framework

Non CSS-in-JS framework

Like semantic-ui, non CSS-in-JS frameworks are supported without extra configuration.

All we have to do is to load global CSS in _document or each page:

views/_document.jsx:

import React from 'react';
import {
  Document,
  Head,
  Main,
} from '@react-ssr/express';

export default class extends Document {
  render() {
    return (
      <html>
        <Head>
          <title>A Sample of Semantic UI React</title>
          <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css" />
        </Head>
        <body>
          <Main />
        </body>
      </html>
    );
  }
}

With Ant Design

In order to enable SSR, we must install babel-plugin-import as devDependencies.

And then, populate .babelrc in your project root:

{
  "presets": [
    "@react-ssr/express/babel"
  ],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css"
      }
    ]
  ]
}

A working example is here: examples/with-jsx-antd

With Emotion

In order to enable SSR, we must install these packages:

And then, populate .babelrc in your project root:

{
  "presets": [
    "@react-ssr/express/babel"
  ],
  "plugins": [
    "emotion"
  ]
}

A working example is here: examples/with-jsx-emotion

With Material UI

We can use material-ui without extra configuration.

A working example is here: examples/with-jsx-material-ui

With styled-components

In order to enable SSR, we must install babel-plugin-styled-components as devDependencies.

And then, populate .babelrc in your project root:

{
  "presets": [
    "@react-ssr/express/babel"
  ],
  "plugins": [
    "styled-components"
  ]
}

A working example is here: examples/with-jsx-styled-components

TypeScript Support

To enable TypeScript engine (.tsx), just put tsconfig.json in your project root directory.

The code of TypeScript will be like this:

package.json:

{
  "scripts": {
    "start": "ts-node server.ts"
  }
}

server.ts:

import express, { Request, Response } from 'express';
import register from '@react-ssr/express/register';

const app = express();

(async () => {
  // register `.tsx` as a view template engine
  await register(app);

  app.get('/', (req: Request, res: Response) => {
    const message = 'Hello World!';
    res.render('index', { message });
  });

  app.listen(3000, () => {
    console.log('> Ready on http://localhost:3000');
  });
})();

views/index.tsx:

interface IndexProps {
  message: string;
}

export default function Index({ message }: IndexProps) {
  return <p>{message}</p>;
}

Packages

package version
@react-ssr/core @react-ssr/core downloads
@react-ssr/express @react-ssr/express downloads
@react-ssr/nestjs-express @react-ssr/nestjs-express downloads

Examples

@react-ssr/express

.jsx

.tsx

@react-ssr/nestjs-express

Real World Examples

Develop examples/<example-folder-name>

$ git clone https://github.com/saltyshiomix/react-ssr.git
$ cd react-ssr
$ lerna bootstrap
$ yarn
$ yarn dev <example-folder-name>

Articles

Introducing an Alternative to NEXT.js

[Express] React as a View Template Engine?

Related

reactjs/express-react-views

Contact

More Repositories

1

nextron

⚡ Next.js + Electron ⚡
TypeScript
3,908
star
2

ark

An easiest authentication system on top of NestJS, TypeORM, NEXT.js(v9.3) and Material UI(v4).
TypeScript
257
star
3

nuxtron

⚡ Nuxt.js + Electron ⚡
TypeScript
219
star
4

create-nextron-app

Create nextron (NEXT.js + Electron) apps in one command ⚡
JavaScript
60
star
5

webpack-typescript-react-starter

Webpack + TypeScript + React = ❤️
JavaScript
59
star
6

nest-crawler

An easiest crawling and scraping module for NestJS
TypeScript
56
star
7

nestpress

A production ready personal blogging system on top of NestJS and NEXT.js
TypeScript
41
star
8

rollup-typescript-react-starter

Rollup + TypeScript + React = ❤️
JavaScript
39
star
9

nextjs-redux-todo-app

A minimal todo app with NEXT.js on the redux architecture
TypeScript
28
star
10

react-ssr-nestjs-starter

An example of @react-ssr/nestjs-express
TypeScript
23
star
11

gfm-preview

Preview your markdown with GitHub API in real time 🎉
JavaScript
19
star
12

web-master

Web mastering tools for my personal services
TypeScript
13
star
13

nerv-ie8-boilerplate

A minimalistic boilerplate of NervJS with IE8+ and React 16 compatibility ⚡
JavaScript
10
star
14

markdown-viewer-for-firefox

[NO MAINTENANCED] GitHub flavored Markdown Viewer for **OLD** Firefox
CSS
10
star
15

LGTMify-extension

Looks Good To Me <3
TypeScript
10
star
16

tiny-pro-tips-for-windows

Tiny but pro tips for Windows
9
star
17

node-npx

A tiny npx alternative for Node.js, which executes local npm package binaries
TypeScript
7
star
18

vue-jwt-auth-example

A starter example of Vue + Vuex + JWT Authentication
TypeScript
6
star
19

editify

A pure implementation of WYSIWYG HTML editor all we needed
TypeScript
5
star
20

resolve-as-bin

Resolve a local npm package as the absolute binary path
TypeScript
5
star
21

yark

Yet another easiest authentication system on top of NestJS, prisma2, react-ssr and Material UI
TypeScript
4
star
22

viteron

⚡ vite + electron ⚡
TypeScript
4
star
23

objectio

A JavaScript object getter and setter with string literals ⚡
TypeScript
3
star
24

react-ssr-jsx-starter

An example of @react-ssr/express
JavaScript
3
star
25

react-ssr-tsx-starter

An example of @react-ssr/express
TypeScript
3
star
26

react-ssr-redux-todo-app

A redux todo example on top of @react-ssr/express
TypeScript
2
star
27

saltyshiomix

1
star
28

create-viteron-app

Create viteron (vite + electron) apps in one command ⚡
JavaScript
1
star