React + Node: Beginner's Guide to Full Stack Dev


React excels at building fast, dynamic frontends. Node.js shines for server-side APIs and microservices. Together, they make a powerful stack for full stack apps.

Let’s walk through integrating React with Node.js:

Serving React Builds

Use Node.js middleware like Express to serve the React app:

// server.js
app.use(express.static(path.join(__dirname, 'client/build')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html));
});

This serves the React build from the /build folder.

Proxying API Requests

Proxy frontend requests to the backend API:

// React
axios.get('/api/users')

// Server 
app.use('/api', apiRouter);

Set up a route forwarding to the API server.

Server-Side Rendering

Use libraries like ReactDOMServer to server-side render components:

// server.js
app.get('/', (req, res) => {
  const jsx = ReactDOMServer.renderToString(<App />);
  
  res.send(jsx); 
});

This serves fully rendered HTML from the React app.

Authentication and Sessions

Share authentication sessions and info between backend and frontend:

// Backend session 
req.session.user = {
  name: 'John'  
};

// React can access via proxy
axios.get('/api/user') // { name: 'John' }

Sessions enable persisting auth across requests.

Summary

  • Use Express to serve React builds
  • Forward requests to Node.js APIs
  • Server-side render for SEO
  • Share auth sessions between frontend and backend

Combining React and Node.js brings together declarative UIs with scalable server infrastructure.