How to integrate frontend Next.js with Node.js and Express.js backend

How to integrate frontend Next.js with Node.js and Express.js backend

To make a frontend created with Next.js work with a backend made using Node.js and Express.js, you need to set up both projects to work together. Here's how to do it step by step:

Step 1: Set up your backend (Node.js with Express.js)

  1. Initialize a Node.js project:

     mkdir backend
     cd backend
     npm init -y
    
  2. Install Express.js and other dependencies:

     npm install express
    
  3. Create your Express app:

     // backend/app.js
     const express = require('express');
     const app = express();
    
     // Define routes
     app.get('/api/data', (req, res) => {
       res.json({ message: 'Hello from backend!' });
     });
    
     module.exports = app;
    
  4. Start your backend server:

     // backend/server.js
     const app = require('./app');
    
     const port = process.env.PORT || 5000;
     app.listen(port, () => {
       console.log(`Server running on port ${port}`);
     });
    

    Run your backend server:

     node server.js
    

Step 2: Set up your frontend (Next.js)

  1. Initialize a Next.js project:

     mkdir frontend
     cd frontend
     npm init -y
    
  2. Install Next.js and other dependencies:

     npm install next react react-dom
    
  3. Create pages and components as needed:

     // frontend/pages/index.js
     import React, { useState, useEffect } from 'react';
    
     const Home = () => {
       const [data, setData] = useState(null);
    
       useEffect(() => {
         fetch('/api/data')
           .then(response => response.json())
           .then(data => setData(data))
           .catch(error => console.error('Error fetching data:', error));
       }, []);
    
       return (
         <div>
           <h1>Frontend with Next.js</h1>
           {data && <p>{data.message}</p>}
         </div>
       );
     };
    
     export default Home;
    

Step 3: Integrate backend with frontend

  1. Proxy requests from frontend to backend: Next.js allows you to proxy API requests during development by adding a next.config.js file in your frontend project:

     // frontend/next.config.js
     module.exports = {
       async rewrites() {
         return [
           {
             source: '/api/:path*',
             destination: 'http://localhost:5000/api/:path*',
           },
         ];
       },
     };
    

    This configuration proxies requests from localhost:3000/api/* to localhost:5000/api/*.

  2. Run both frontend and backend concurrently: You can use a tool like concurrently to run both projects simultaneously. Install it:

     npm install -g concurrently
    

    Then, add a script to your frontend package.json:

     "scripts": {
       "dev": "concurrently \"next dev\" \"node backend/server.js\""
     }
    

    Now, you can start both frontend and backend with a single command:

     npm run dev
    

With these steps, you've connected your Next.js frontend to a Node.js and Express.js backend. The frontend talks to the backend using API requests, and you can work on and run both parts at the same time during development.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!