Node.js and Next.js Illustrated by Creating a RESTful API

Node.js is a JavaScript runtime that enables server-side development, while Next.js is a framework built on top of React for creating server-rendered and statically generated web applications. Together, they provide a powerful combination for building full-stack applications that leverage JavaScript both on the client and server sides.

Here is a simple example demonstrating how to create a RESTful API using Node.js and then consume that API from a Next.js application.

Step 1: Setting Up the Node.js RESTful API

1. Create a new directory for your Node.js API

bashCopy codemkdir node-api
cd node-api

2. Initialize a new Node.js project

bashCopy codenpm init -y

3. Install necessary packages

You’ll need express for setting up the server:

bashCopy codenpm install express cors

4. Create the API server

Create a file named server.js and add the following code:

// server.js
const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 5000;

// Middleware
app.use(cors());
app.use(express.json()); // To parse JSON request bodies

// Sample data
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];

// GET endpoint to fetch all users
app.get('/api/users', (req, res) => {
  res.json(users);
});

// GET endpoint to fetch a user by ID
app.get('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id, 10);
  const user = users.find((u) => u.id === userId);
  
  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }
  
  res.json(user);
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

5. Run the API server

bashCopy codenode server.js

Your API will now be running on http://localhost:5000, and you can access the endpoints:

  • GET http://localhost:5000/api/users to fetch all users
  • GET http://localhost:5000/api/users/1 to fetch a user by ID

Step 2: Setting Up the Next.js Application

1. Create a new Next.js application

Open a new terminal and run:

bashCopy codenpx create-next-app@latest next-app
cd next-app

2. Create a page to consume the API

Open pages/index.js and modify it as follows:

// pages/index.js
import { useEffect, useState } from 'react';

export default function Home() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await fetch('http://localhost:5000/api/users');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error('Error fetching users:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

3. Run the Next.js application

In the terminal, navigate to the Next.js app directory (if not already there) and run:

bashCopy codenpm run dev

The Next.js app will now be running on http://localhost:3000.

Step 3: Access the Application

  1. Open your browser and navigate to http://localhost:3000.
  2. You should see a list of users fetched from your Node.js API displayed on the page.

This is a simple RESTful API created with Node.js using Express, and a Next.js application that consumes this API to display data.

To enhance the understanding, here is the same example but using Python with Flask framework instead of node.js, then also consumed by a Next.js application.

create the API server

# app.py
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

# Sample data
users = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"},
]

# GET endpoint to fetch all users
@app.route('/api/users', methods=['GET'])
def get_users():
    return jsonify(users)

# GET endpoint to fetch a user by ID
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = next((u for u in users if u['id'] == user_id), None)
    if user is None:
        return jsonify({"message": "User not found"}), 404
    return jsonify(user)

# Start the server
if __name__ == '__main__':
    app.run(debug=True, port=5000)

Run the API server

bashCopy codepython app.py

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.