React Storefront
|

Serving React Storefront Apps from Express

Though we recommend hosting your React Storefront app on Moovweb's XDN, you can also host your app using Express.

Development

If you used create-react-storefront to create your app, it contains an npm script for running your app in express during local development:

$ npm run start:express

Your app's express entry point is located in src/express.js.

Middleware and Routing

When using express, we recommend keeping your code DRY by using react-storefront's isomorphic router rather than express's. You can delegate routing to react-storefront by installing the react-storefront-middleware:

import express from 'express'
import bodyParser from 'body-parser'
import theme from './theme'
import model from './AppModel'
import App from './App'
import router from './routes'
import Server from 'react-storefront/Server'
import reactStorefrontMiddleware from 'react-storefront-middleware'

const app = express()

app.use(bodyParser.json())

app.use(
  reactStorefrontMiddleware(
    new Server({ 
      theme, 
      model, 
      App, 
      router
    }) 
  )
)

Request and Response Objects

The request and response parameters passed to your handlers are instances of express's Request and Response classes, but in most cases you should return a JSON object instead of calling response.send. This allows react-storefront to decide whether or not to return the JSON response verbatim or use returned data to do server-side rendering.

export default function homeHandler(params, request, response) {
  // request and response are instances of express's Request and Response classes
  return { title: 'Home' } // return data corresponding to your AppModel class
}