React excels at constructing quick, dynamic frontends. Node.js shines for server-side APIs and microservices. Collectively, they make a strong stack for full stack apps.
Let’s stroll by way of integrating React with Node.js:
Serving React Builds
Use Node.js middleware like Categorical to serve the React app:
// server.js
app.use(categorical.static(path.be a part of(__dirname, 'consumer/construct')));
app.get('*', (req, res) => {
res.sendFile(path.be a part of(__dirname, 'consumer/construct', 'index.html));
});
This serves the React construct from the /construct
folder.
Proxying API Requests
Proxy frontend requests to the backend API:
// React
axios.get('/api/customers')
// Server
app.use('/api', apiRouter);
Arrange a route forwarding to the API server.
Server-Facet Rendering
Use libraries like ReactDOMServer to server-side render parts:
// server.js
app.get('/', (req, res) => {
const jsx = ReactDOMServer.renderToString(<App />);
res.ship(jsx);
});
This serves absolutely rendered HTML from the React app.
Authentication and Classes
Share authentication classes and data between backend and frontend:
// Backend session
req.session.consumer = {
identify: 'John'
};
// React can entry through proxy
axios.get('/api/consumer') // { identify: 'John' }
Classes allow persisting auth throughout requests.
Abstract
- Use Categorical to serve React builds
- Ahead requests to Node.js APIs
- Server-side render for web optimization
- Share auth classes between frontend and backend
Combining React and Node.js brings collectively declarative UIs with scalable server infrastructure.