UNPKG

7.33 kBMarkdownView Raw
1# express-react-middleware
2A middleware able to render react components in your server with node.js as views, it is also able to render routes in an array of routes in react-router.
3
4## Why?
5Have you ever saw that whenever you're making a new project or when an existing project have to be updated you must to follow and do a lot of steps to achieve the desired outcome in the server when you want to apply SSR? Well, this middleware avoid having to remember all those steps even react-router.
6
7## What are the target projects?
8- For existing projects.
9- For new projects.
10- Projects who want to have better control of what components needs to be rendered in a specific resource.
11- Projects who want to update their old configurations.
12
13## Pre-requisites
14 1. A html file to use as template.
15 2. The html file must include a div or any element with an id attribute to mount the component.
16 3. The components path or a file with all the routes. (see react-router v4 docs)
17
18## Installation
19
20``npm install --save express-react-middleware``
21or
22``yarn add express-react-middleware``
23
24## Usage
25
26There are 2 ways to use it in and is using a routes config file or by resolving the components.
27
28#### template
29The template is just an html file with a basic markup like this:
30```html
31<!DOCTYPE html>
32<html>
33 <head>
34 <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
35 <meta http-equiv="X-UA-Compatible" content="IE=10; IE=9; IE=8; IE=7; IE=EDGE">
36 <meta charset="utf-8"><meta name="description" content="">
37 <meta name="keywords" content="">
38 <meta name="author" content="">
39 <title></title>
40 </head>
41 <body>
42 <div id="root">Default template, this doesn't render any component</div>
43 <script src="./bundle.js"></script>
44 </body>
45</html>
46```
47
48This is an example of how to require a template *(synchronous, recommended way)*:
49
50```javascript
51import { readFileSync } from 'fs'
52import { resolve } from 'path'
53
54const root = (path) => resolve(__dirname, path)
55
56let template = (() => {
57 try {
58 return readFileSync(root('./index.html'), { encoding: 'UTF-8' });
59 } catch (err) {
60 // If the template file *.html is not found then it throws an error instead of continuing the flow.
61 throw err;
62 }
63})();
64```
65
66#### options
67
68| name | type | optional | required | sync render | async render | description |
69| ---- | ---- | -------- | -------- | ----------- | ------------ | ----------- |
70| **templateHTML** | string | x | √ | √ | √ | The instance of the html file
71| **mountId** | object | x | √ | √ | √ | The id of the element where the component or components will be rendered
72| **componentsPath** | string | √ | (√/x) | √ | √ | Here you have to pass the absolute path to locate the components. (required if **routes** option is not set) If routes option is present this option is ignored.
73| **routes** | array | √ | (√/x) | √ | √ | the routes file used in react-router to match and render the components. (required if **componentsPath** is not set)
74
75Example of how the options should be written:
76
77```javascript
78
79import { resolve } from 'path'
80const root = (path) => resolve(__dirname, path)
81
82let options = {
83 templateHTML: template,
84 mountId: "root",
85 componentsPath: root("path/to/your/components")
86};
87
88// or with a file with the routes used in react-router:
89
90import routes from './routes'
91
92// ...
93
94let options = {
95 templateHTML: template,
96 mountId: "root",
97 routes: { collection: routes, /*extractComponent: boolean, default false*/ }
98};
99```
100
101#### Use it in your app, router or elsewhere you want:
102```javascript
103import reactMiddleware from 'express-react-middleware'
104
105// ...
106
107app.use(reactMiddleware(options));
108```
109
110#### Render:
111
112When the middleware has already been set you will find a new function property with the name **render** in the *request* object.
113
114###### Arguments:
115The `req.render` could take some arguments:
116
117| name | type | optional | used in sync render | used in async render |
118| -------------- | -------- | -------- | ------------------- | -------------------- |
119| **component** | string | √ | √ | √ |
120| **props** | object | √ | √ | √ |
121| **callback** | function | √ | x | √ |
122
123###### Returns:
124When you have used the `req.render` function it will return an object with almost 6 properties:
125
126| name | type | description |
127| ------------- | -------- | ----------- |
128| **html** | string | value containing the template html with the component rendered, the initial state and props. |
129| **context** | object | used in redirections or to set customs status code to the response. |
130| **component** | object | The component found. |
131| **props** | object | The properties that you passed before the render process |
132| **template** | string | The original template value without any modification. |
133| **changes** | object | Contains almost all the changes occurred |
134
135###### Synchronous:
136```javascript
137app.get('/contact', (req, res) => {
138 // 1.
139 let { html, context } = req.render('contact');
140 // ...
141
142 // 2.
143 let { html, context } = req.render('contact', { title: 'Contact', msg: 'Welcome!' });
144 // ...
145
146 // 3.
147 let { html, context } = req.render('contact', null);
148 // ...
149
150 // 4. This maner is only valid if you have set the "routes" option in the middleware cause it uses "req.url" to find the component instead of having to write the name of a component react file:
151 let { html, context } = req.render();
152 // ...
153});
154```
155
156###### Asynchronous:
157```javascript
158app.get('/contact', (req, res) => {
159 // 1. contact is the name of a component and it is resolved with "componentsPath" (Only if routes option is not set).
160 req.render('contact', ({html, context}) => {
161 // ...
162 });
163
164 // 2.
165 req.render('contact', {title: 'Contact', msg: 'Welcome!'}, ({html, context}) => {
166 // ...
167 });
168
169 // 3.
170 req.render('contact', null, ({html, context}) => {
171 // ...
172 });
173
174 // 4. This maner is only valid if you have set the `routes` option in the middleware cause it uses `req.url` to find the component instead of having to write the name of a component react file:
175  req.render(({html, context}) => {
176 // ...
177 });
178})
179```
180
181###### Response:
182
183``` javascript
184app.get('/contact', (req, res) => {
185 // ... {html, context}
186
187 if (context.url) {
188 res.redirect(context.status, context.url);
189 // context.url is used to redirect or context.status when you need to send a specific status in your routes.
190 } else {
191 res.status(context.status).send(html);
192 // html is a string value containing the template html also it contains the component rendered.
193 }
194});
195```
196## Tests:
197``` bash
198npm run test
199```
200![Image of Tests](https://raw.githubusercontent.com/normancarcamo/express-react-middleware/master/tests_preview.png)
201<br/>
202:+1:
203
204## Examples:
205See [examples folder](https://github.com/normancarcamo/express-react-middleware/tree/master/examples)
206
207## Maintainers:
208
209![Image of Mantainer](http://s.gravatar.com/avatar/c3d34f6dbeeef3c39942d0ecb1247228?s=80)<br/>
210[Norman Carcamo](https://github.com/normancarcamo)<br/>
211[NPM - modules](https://www.npmjs.com/~normanfx)<br/>
\No newline at end of file