• This repository has been archived on 22/Jan/2020
  • Stars
    star
    1,449
  • Rank 32,472 (Top 0.7 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 5 years ago

Reviews

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

Repository Details

a composite render engine for universal (isomorphic) express apps to render both plain react views and react-router views

react-engine

Build Status

What is react-engine?

  • a react render engine for Universal (previously Isomorphic) JavaScript apps written with express
  • renders both plain react views and optionally react-router views
  • enables server rendered views to be client mountable

Install

# In your express app, react-engine needs to be installed alongside react/react-dom (react-router is optional)
$ npm install react-engine react react-dom react-router --save

Usage On Server Side

Setup in an Express app
var Express = require('express');
var ReactEngine = require('react-engine');

var app = Express();

// create an engine instance
var engine = ReactEngine.server.create({
  /*
    see the complete server options spec here:
    https://github.com/paypal/react-engine#server-options-spec
  */
});

// set the engine
app.engine('.jsx', engine);

// set the view directory
app.set('views', __dirname + '/views');

// set jsx or js as the view engine
// (without this you would need to supply the extension to res.render())
// ex: res.render('index.jsx') instead of just res.render('index').
app.set('view engine', 'jsx');

// finally, set the custom view
app.set('view', require('react-engine/lib/expressView'));
Setup in a KrakenJS app's config.json
{
  "express": {
    "view engine": "jsx",
    "view": "require:react-engine/lib/expressView",
  },
  "view engines": {
    "jsx": {
      "module": "react-engine/lib/server",
      "renderer": {
        "method": "create",
        "arguments": [{
          /*
            see the complete server options spec here:
            https://github.com/paypal/react-engine#server-options-spec
          */
        }]
      }
    }
  }
}
Server options spec

Pass in a JavaScript object as options to the react-engine's server engine create method. The options object should contain the mandatory routes property with the route definition.

Additionally, it can contain the following optional properties,

  • docType: <String> - a string that can be used as a doctype (Default: <!DOCTYPE html>). (docType might not make sense if you are rendering partials/sub page components, in that case you can pass an empty string as docType)

  • routesFilePath: <String> - path for the file that contains the react router routes. react-engine uses this behind the scenes to reload the routes file in cases where express's app property view cache is false, this way you don't need to restart the server every time a change is made in the view files or routes file.

  • renderOptionsKeysToFilter: <Array> - an array of keys that need to be filtered out from the data object that gets fed into the react component for rendering. more info

  • performanceCollector: <Function> - to collects perf stats

  • scriptLocation: <String> - where in the HTML you want the client data (i.e. <script>var __REACT_ENGINE__ = ... </script>) to be appended (Default: body). If the value is undefined or set to body the script is placed before the </body> tag. The only other value is head which appends the script before the </head> tag.

  • staticMarkup: <Boolean> - a boolean that indicates if render components without React data attributes and client data. (Default: false). This is useful if you want to render simple static page, as stripping away the extra React attributes and client data can save lots of bytes.

  • scriptType: <String> - a string that can be used as the type for the script (if it is included, which is only if staticMarkup is false). (Default: application/json).

Rendering views on server side
var data = {}; // your data model

// for a simple react view rendering
res.render(viewName, data);

// for react-router rendering
// pass in the `url` and react-engine
// will run the react-router behind the scenes.
res.render(req.url, data);

Usage On Client Side (Mounting)

// assuming we use a module bundler like `webpack` or `browserify`
var client = require('react-engine/lib/client');

// finally, boot whenever your app is ready
// example:
document.addEventListener('DOMContentLoaded', function onLoad() {

  // `onBoot` - Function (optional)
  // returns data that was used
  // during rendering as the first argument
  // the second argument is the `history` object that was created behind the scenes
  // (only available while using react-router)
  client.boot(/* client options object */, function onBoot(data, history) {

  });
};

// if the data is needed before booting on
// client, call `data` function anytime to get it.
// example:
var data = client.data();
Client options spec

Pass in a JavaScript object as options to the react-engine's client boot function. It can contain the following properties,

  • routes : required - Object - the route definition file.
  • viewResolver : required - Function - a function that react-engine needs to resolve the view file. an example of the viewResolver can be found here.
  • mountNode : optional - HTMLDOMNode - supply a HTML DOM Node to mount the server rendered component in the case of partial/non-full page rendering.
  • history : optional - Object - supply any custom history object to be used by the react-router.

Data for component rendering

The actual data that gets fed into the component for rendering is the renderOptions object that express generates.

If you don't want to pass all that data, you can pass in an array of object keys or dot-lookup paths that react-engine can filter out from the renderOptions object before passing it into the component for rendering.

// example of using `renderOptionsKeysToFilter` to filter `renderOptions` keys
var engine = ReactEngine.server.create({
  renderOptionsKeysToFilter: [
    'mySensitiveData',
    'somearrayAtIndex[3].deeply.nested'
  ],
  routes: require(path.join(__dirname + './reactRoutes'))
});

Notes:

  • The strings renderOptionsKeysToFilter will be used with lodash.unset, so they can be either plain object keys for first-level properties of renderOptions, or dot-separated "lookup paths" as shown in the lodash.unset documentation. Use these lookup paths to filter out nested sub-properties.
  • By default, the following three keys are always filtered out from renderOptions no matter whether renderOptionsKeysToFilter is configured or not.
    • settings
    • enrouten
    • _locals

Handling redirects and route not found errors on the server side

While using react-router, it matches the url to a component based on the app's defined routes. react-engine captures the redirects and not-found cases that are encountered while trying to run the react-router's match function on the server side.

To handle the above during the lifecycle of a request, add an error type check in your express error middleware. The following are the three types of error that get thrown by react-engine:

Error Type Description
MATCH_REDIRECT** indicates that the url matched to a redirection
MATCH_NOT_FOUND indicates that the url did not match to any component
MATCH_INTERNAL_ERROR indicates that react-router encountered an internal error

** for MATCH_REDIRECT error, redirectLocation property of the err has the new redirection location

// example express error middleware
app.use(function(err, req, res, next) {
  console.error(err);

  // http://expressjs.com/en/guide/error-handling.html
  if (res.headersSent) {
    return next(err);
  }

  if (err._type && err._type === ReactEngine.reactRouterServerErrors.MATCH_REDIRECT) {
    return res.redirect(302, err.redirectLocation);
  }
  else if (err._type && err._type === ReactEngine.reactRouterServerErrors.MATCH_NOT_FOUND) {
    return res.status(404).send('Route Not Found!');
  }
  else {
    // for ReactEngine.reactRouterServerErrors.MATCH_INTERNAL_ERROR or
    // any other error we just send the error message back
    return res.status(500).send(err.message);
  }
});

Yeoman Generator

There is a Yeoman generator available to create a new express or KrakenJS application which uses react-engine: generator-react-engine.

Performance Profiling

Pass in a function to the performanceCollector property to collect the stats object for every render.

stats

The object that contains the stats info for each render by react-engine. It has the below properties.

  • name - Name of the template or the url in case of react router rendering.
  • startTime - The start time of render.
  • endTime - The completion time of render.
  • duration - The duration taken to render (in milliseconds).
// example
function collector(stats) {
  console.log(stats);
}

var engine = require('react-engine').server.create({
  routes: './routes.jsx'
  performanceCollector: collector
});

Notes

  • On the client side, the state is exposed in a script tag whose id is react-engine-props
  • When Express's view cache app property is false (mostly in non-production environments), views are automatically reloaded before render. So there is no need to restart the server for seeing the changes.
  • You can use js as the engine if you decide not to write your react views in jsx.
  • Blog on react-engine
  • You can add nonce in _locals, which will be added in script tag that gets injected into the server rendered pages, like res.locals.nonce = 'nonce value'

License

Apache Software License v2.0

More Repositories

1

glamorous

DEPRECATED: 💄 Maintainable CSS with React
JavaScript
3,640
star
2

junodb

JunoDB is PayPal's home-grown secure, consistent and highly available key-value store providing low, single digit millisecond, latency at any scale.
Go
2,565
star
3

accessible-html5-video-player

Accessible HTML5 Video Player
JavaScript
2,451
star
4

squbs

Akka Streams & Akka HTTP for Large-Scale Production Deployments
Scala
1,433
star
5

PayPal-node-SDK

node.js SDK for PayPal RESTful APIs
JavaScript
1,279
star
6

paypal-checkout-components

please submit Issues about the PayPal JS SDK here: https://github.com/paypal/paypal-js/issues
JavaScript
1,270
star
7

gatt

Gatt is a Go package for building Bluetooth Low Energy peripherals
Go
1,135
star
8

PayPal-iOS-SDK

Accept credit cards and PayPal in your iOS app
Objective-C
974
star
9

gnomon

Utility to annotate console logging statements with timestamps and find slow processes
JavaScript
932
star
10

PayPal-Android-SDK

Accept PayPal and credit cards in your Android app
Java
824
star
11

bootstrap-accessibility-plugin

Accessibility Plugin for Bootstrap 3 and Bootstrap 3 as SubModule
HTML
789
star
12

PayPal-Python-SDK

Python SDK for PayPal RESTful APIs
Python
702
star
13

AATT

Automated Accessibility Testing Tool
JavaScript
601
star
14

PayPal-Ruby-SDK

Ruby SDK for PayPal RESTful APIs
Ruby
593
star
15

ipn-code-samples

PHP
561
star
16

seifnode

C++
545
star
17

PayPal-NET-SDK

.NET SDK for PayPal's RESTful APIs
C#
535
star
18

PayPal-Java-SDK

Java SDK for PayPal RESTful APIs
Java
535
star
19

data-contract-template

Template for a data contract used in a data mesh.
460
star
20

Checkout-PHP-SDK

PHP SDK for Checkout RESTful APIs
PHP
418
star
21

hera

High Efficiency Reliable Access to data stores
Go
289
star
22

SeLion

Enabling Test Automation in Java
Java
281
star
23

nemo-core

Selenium-webdriver based automation in node.js
JavaScript
261
star
24

support

An evented server framework designed for building scalable and introspectable services, built at PayPal.
Python
261
star
25

PayPal-Cordova-Plugin

PayPal SDK Cordova/Phonegap Plugin
Objective-C
248
star
26

gimel

Big Data Processing Framework - Unified Data API or SQL on Any Storage
Scala
245
star
27

scala-style-guide

Style Guidelines for PayPal Scala Applications
240
star
28

merchant-sdk-php

PHP SDK for integrating with PayPal's Express Checkout / MassPay / Web Payments Pro APIs
PHP
230
star
29

paypal-js

Loading wrapper and TypeScript types for the PayPal JS SDK
TypeScript
229
star
30

paypal-rest-api-specifications

This repository contains the specification files for PayPal REST APIs.
192
star
31

resteasy-spring-boot

RESTEasy Spring Boot Starter
Java
188
star
32

Checkout-Java-SDK

PayPal Checkout Java SDK
Java
182
star
33

autosklearn-zeroconf

autosklearn-zeroconf is a fully automated binary classifier. It is based on the AutoML challenge winner auto-sklearn. Give it a dataset with known outcomes (labels) and it returns a list of predicted outcomes for your new data. It even estimates the precision for you! The engine is tuning massively parallel ensemble of machine learning pipelines for best precision/recall.
Python
171
star
34

skipto

SkipTo is a replacement for your old classic "Skipnav" link. Once installed on a site, the script dynamically determines the most important places on the page and presents them to the user in a drop-down menu.
HTML
152
star
35

TLS-update

Documentation & tools for the upcoming TLSv1.2 required update
Java
148
star
36

Checkout-NET-SDK

.NET SDK for Checkout RESTful APIs
C#
139
star
37

cascade

Common Libraries & Patterns for Scala Apps @ PayPal
Scala
129
star
38

merchant-sdk-ruby

Ruby
110
star
39

heap-dump-tool

Tool to sanitize data from Java heap dumps.
Java
110
star
40

NNAnalytics

NameNodeAnalytics is a self-help utility for scouting and maintaining the namespace of an HDFS instance.
Java
110
star
41

paypal-smart-payment-buttons

Smart Payment Buttons
JavaScript
108
star
42

yurita

Anomaly detection framework @ PayPal
Scala
106
star
43

InnerSourceCommons

DEPRECATED - old repo for InnerSourceCommons website. Moved to https://github.com/InnerSourceCommons/innersourcecommons.org
JavaScript
105
star
44

adaptivepayments-sdk-php

PHP SDK for integrating with PayPal's AdaptivePayments API
PHP
101
star
45

fullstack-phone

A dual-module phone number system with dynamic regional metadata ☎️
JavaScript
90
star
46

sdk-core-php

for classic PHP SDKs.
PHP
87
star
47

paypal-here-sdk-android-distribution

Add credit card (swipe & key-in) capabilities to your Android app
Java
84
star
48

merchant-sdk-dotnet

C#
83
star
49

paypal-here-sdk-ios-distribution

Add credit card (tap, insert, swipe & key-in) capabilities to your iOS app
Objective-C
82
star
50

payflow-gateway

Repository to store the Payflow Gateway and PayPal Payments Pro SDKs.
C#
80
star
51

sdk-packages

Binary packages for deprecated SDKs.
77
star
52

android-checkout-sdk

Kotlin
77
star
53

Iguanas

Iguanas is a fast, flexible and modular Python package for generating a Rules-Based System (RBS) for binary classification use cases.
Jupyter Notebook
74
star
54

paypal-android

One merchant integration point for all of PayPal's services
Kotlin
72
star
55

legalize.js

JavaScript object validation for browsers + node
JavaScript
70
star
56

paypalcheckout-ios

Need to add Native Checkout to your iOS Application? We can help!
Ruby
70
star
57

paypal-sdk-client

Shared config for PayPal/Braintree client SDKs
JavaScript
65
star
58

load-watcher

Load watcher is a cluster-wide aggregator of metrics, developed for Trimaran: Real Load Aware Scheduler in Kubernetes.
Go
63
star
59

dce-go

Docker Compose Executor to launch pod of docker containers in Apache Mesos.
Go
63
star
60

merchant-sdk-java

Java SDK for integrating with PayPal's Express Checkout / MassPay / Web Payments Pro APIs
Java
62
star
61

sdk-core-java

for classic Java SDKs.
Java
61
star
62

paypal-ios

One merchant integration point for all of PayPal's services
Swift
59
star
63

gorealis

Version 1 of a Go library for interacting with the Aurora Scheduler
Go
58
star
64

scorebot

CSS
57
star
65

PPExtensions

Set of iPython and Jupyter extensions to improve user experience
Python
50
star
66

paypal-checkout-demo

Demo app for paypal-checkout
JavaScript
49
star
67

dione

Dione - a Spark and HDFS indexing library
Scala
49
star
68

Payouts-PHP-SDK

PHP SDK for Payouts RESTful APIs
PHP
49
star
69

pdt-code-samples

Visual Basic
48
star
70

butterfly

Application transformation tool
Java
47
star
71

Payouts-NodeJS-SDK

NodeJS SDK for Payouts RESTful APIs
JavaScript
47
star
72

digraph-parser

Java parser for digraph DSL (Graphviz DOT language)
Java
44
star
73

paypalhttp_php

PHP
43
star
74

tech-talks

Place for all PayPalX presentations, tech talks, and tutorials, and the sample code and apps used in those.
ColdFusion
38
star
75

Illuminator

iOS Automator
Swift
38
star
76

paypal-sdk-release

Unified SDK wrapper module for tests, shared build config, and deploy
JavaScript
37
star
77

PayPal-REST-API-issues

Issue tracking for REST API bugs, features, and documentation requests.
37
star
78

paypal-messaging-components

PayPal JavaScript SDK - messaging components
JavaScript
37
star
79

ionet

ionet is a bridge between the Go stdlib's net and io packages
Go
37
star
80

paypal-access

Examples and code for PayPal Access
Python
36
star
81

horizon

An SBT plugin to help with building, testing, analyzing and releasing Scala
Scala
35
star
82

Payouts-Java-SDK

Java SDK for Payouts RESTful APIs
Java
35
star
83

genio

Genio is an extensible tool that can generate code to consume APIs in multiple programming languages based on different API specification formats.
Ruby
35
star
84

mirakl-hyperwallet-connector

The Hyperwallet Mirakl Connector (HMC) is a self-hosted solution that mediates between a Mirakl marketplace solution and the Hyperwallet (PayPal) payout platform.
Java
34
star
85

openapilint

Node.js linter for OpenAPI specs
JavaScript
31
star
86

paypal-sdk-constants

JavaScript
27
star
87

sdk-core-ruby

Core Library for PayPal Ruby SDKs
Ruby
27
star
88

go.crypto

Go crypto packages
Go
26
star
89

PayPal-PHP-SDK

PHP SDK for PayPal RESTful APIs
PHP
26
star
90

nemo-view

View interface for the Nemo automation framework
JavaScript
26
star
91

Gibberish-Detector-Java

A small program to detect gibberish using a Markov Chain
Java
26
star
92

nemo-accessibility

Automate Accessibility testing within your environment (Localhost)
JavaScript
25
star
93

Payouts-Python-SDK

Python SDK for Payouts RESTful APIs
Python
25
star
94

here-sideloader-api-samples

Sideloader API samples that enable to integrate PayPal Here into other apps
Objective-C
24
star
95

couchbasekafka

Couchbase Kafka Adapter
Java
24
star
96

baler

Bundle assets into iOS static libraries
Python
22
star
97

invoice-sdk-php

PHP SDK for integrating with PayPal's Invoicing API
PHP
21
star
98

Payouts-DotNet-SDK

DotNet SDK for Payouts RESTful APIs
C#
20
star
99

paypal-funding-components

PayPal JavaScript SDK Funding Components
JavaScript
20
star
100

squbs-scala-seed.g8

Scala giter8 Template for Squbs
Scala
20
star