Shahaf
Shahaf

Reputation: 357

React App and Backend API best practice

I have React App with React Router for client side routing and Rest API over Express Backend (The React App is using the API to get data)

Currently my Express routing configured as '/' goes to html file that wrap the React javascript file and after that routing to the backend API

I have react router for client side routing and it makes routing complicated.

I'm wondering if it'll be better to separate my App to two: React App and Backend API and run two node instances

What are the best practices ?

Upvotes: 2

Views: 3303

Answers (1)

thebearingedge
thebearingedge

Reputation: 681

Here is a simple server.js I am using for one of my projects.

// server.js
import express from 'express'
import router from './api/router'
import { port } from './config'


express()
  .use(express.static(__dirname + '/public'))
  .use('/api', router)
  .use('*', (_, res) => res.sendFile(__dirname + '/public/index.html'))
  .listen(port, _ => console.log(`listening on ${port}`))

Inside of public is my index.html, styles.css, and bundle.js. On app.use('*', ...) the server will send index.html.

A more thorough approach would be to write an express middleware that uses react-router's match function for server-side rendering instead of just sending index.html on *. For example:

import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from './route-config' // <-- react routes

export const renderPage = ({ url }, res) =>

  match({ routes, location: url }, (err, redirect, renderProps) => {

    if (err)
      return res.status(500).send(err.message)

    if (redirect)
      return res.redirect(302, redirect.pathname + redirect.search)

    if (renderProps) {
      return res
        .status(200)
        .send(renderToString(<RouterContext { ...renderProps }/>))
    }

    res.status(404).send('Not found')
  })

That approach gives you the ability to properly handle 404's and redirects.

Upvotes: 3

Related Questions