Logo

dev-resources.site

for different kinds of informations.

How to Create and Consume a REST API in Next.js

Published at
1/13/2025
Categories
api
nextjs
mongodb
javascript
Author
dhrumitdk
Categories
4 categories in total
api
open
nextjs
open
mongodb
open
javascript
open
Author
9 person written this
dhrumitdk
open
How to Create and Consume a REST API in Next.js

Next.js is widely known for its capabilities in server-side rendering and static site generation, but it also allows you to build full-fledged applications with server-side functionality, including APIs. With Next.js, you can easily create a REST API directly within the framework itself, which can be consumed by your frontend application or any external service.

In this blog post, weā€™ll walk through how to create a simple REST API in Next.js and how to consume that API both within your application and externally. By the end, youā€™ll have a solid understanding of how to build and interact with APIs in a Next.js project.

Creating a REST API in Next.js

Next.js provides a straightforward way to build API routes using the pages/api directory. Each file you create in this directory automatically becomes an API endpoint, where the file name corresponds to the endpoint's route.

Step 1: Set up a New Next.js Project

If you donā€™t have a Next.js project yet, you can easily create one by running the following commands:

npx create-next-app my-next-api-project
cd my-next-api-project
npm install mongodb
npm run dev
Enter fullscreen mode Exit fullscreen mode

This will create a basic Next.js application and start the development server. You can now start building your REST API.

Step 2: Create Your API Route

In Next.js, API routes are created within the pages/api folder. For example, if you want to create a simple API for managing users, you could create a file named users.js inside the pages/api directory.

mkdir pages/api
touch pages/api/users.js
Enter fullscreen mode Exit fullscreen mode

Inside users.js, you can define the API route. Hereā€™s a simple example that responds with a list of users:

// pages/api/users.js
export default function handler(req, res) {
  // Define a list of users
  const users = [
    { id: 1, name: "John Doe", email: "[email protected]" },
    { id: 2, name: "Jane Smith", email: "[email protected]" },
  ];

  // Send the list of users as a JSON response
  res.status(200).json(users);
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create MongoDB Connection Utility
To ensure you're not opening a new database connection with every API request, itā€™s best to create a reusable MongoDB connection utility. You can do this by creating a lib/mongodb.js file, which handles connecting to your MongoDB instance and reusing the connection.

Hereā€™s an example of a simple MongoDB connection utility:

// lib/mongodb.js
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

let clientPromise;

if (process.env.NODE_ENV === 'development') {
  // In development, use a global variable so the MongoDB client is not re-created on every reload
  if (global._mongoClientPromise) {
    clientPromise = global._mongoClientPromise;
  } else {
    global._mongoClientPromise = client.connect();
    clientPromise = global._mongoClientPromise;
  }
} else {
  // In production, itā€™s safe to use the MongoClient directly
  clientPromise = client.connect();
}

export default clientPromise;
Enter fullscreen mode Exit fullscreen mode

Step 4: Set Up the MongoDB URI in .env.local
To securely store your MongoDB URI, create a .env.local file in the root directory of your project. Add your MongoDB URI here:

# .env.local
MONGODB_URI=mongodb+srv://<your-user>:<your-password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
Enter fullscreen mode Exit fullscreen mode

If youā€™re using MongoDB Atlas, you can get this URI from the Atlas dashboard.

Step 5: Create an API Route to Interact with MongoDB

You can handle different HTTP methods (GET, POST, PUT, DELETE) in your API by inspecting the req.method property. Hereā€™s an updated version of the users.js file that responds differently based on the HTTP method.

// pages/api/users.js
import clientPromise from '../../lib/mongodb';

export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db(); // Connect to the default database (replace with your DB name if needed)
  const usersCollection = db.collection('users'); // 'users' collection in MongoDB

  switch (req.method) {
    case 'GET':
      // Retrieve all users
      try {
        const users = await usersCollection.find({}).toArray();
        res.status(200).json(users);
      } catch (error) {
        res.status(500).json({ message: 'Error fetching users' });
      }
      break;

    case 'POST':
      // Add a new user
      try {
        const { name, email } = req.body;
        const newUser = await usersCollection.insertOne({ name, email });
        res.status(201).json(newUser.ops[0]);
      } catch (error) {
        res.status(500).json({ message: 'Error creating user' });
      }
      break;

    case 'PUT':
      // Update an existing user by ID
      try {
        const { id, name, email } = req.body;
        const updatedUser = await usersCollection.updateOne(
          { _id: new ObjectId(id) },
          { $set: { name, email } }
        );
        res.status(200).json(updatedUser);
      } catch (error) {
        res.status(500).json({ message: 'Error updating user' });
      }
      break;

    case 'DELETE':
      // Delete a user by ID
      try {
        const { id } = req.body;
        await usersCollection.deleteOne({ _id: new ObjectId(id) });
        res.status(200).json({ message: 'User deleted' });
      } catch (error) {
        res.status(500).json({ message: 'Error deleting user' });
      }
      break;

    default:
      res.status(405).json({ message: 'Method Not Allowed' });
      break;
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, your API is capable of handling GET, POST, PUT, and DELETE requests to manage users.

  • GET fetches all users.
  • POST adds a new user.
  • PUT updates an existing user.
  • DELETE removes a user.

Step 6: Testing the API

Now that youā€™ve set up the API, you can test it by making requests using a tool like Postman or cURL. Here are the URLs for each method:

  • GET request to /api/users to retrieve the list of users.
  • POST request to /api/users to create a new user (send user data in the request body).
  • PUT request to /api/users to update an existing user (send user data in the request body).
  • DELETE request to /api/users to delete a user (send the user ID in the request body).

Step 5: Protecting Your API (Optional)

You might want to add some basic authentication or authorization to your API to prevent unauthorized access. You can do this easily by inspecting the req.headers or using environment variables to store API keys. For instance:

export default function handler(req, res) {
  const apiKey = req.headers['api-key'];

  if (apiKey !== process.env.API_KEY) {
    return res.status(403).json({ message: 'Forbidden' });
  }

  // Continue with the request handling as usual
}
Enter fullscreen mode Exit fullscreen mode

Consuming the REST API in Your Next.js Application

Now that you have an API set up, letā€™s look at how to consume it within your Next.js application. There are multiple ways to consume the API, but the most common approach is using fetch (or libraries like Axios) to make HTTP requests.

Step 1: Fetch Data with getServerSideProps

If you need to fetch data from your API on the server-side, you can use Next.jsā€™s getServerSideProps to fetch data before rendering the page. Hereā€™s an example of how you can consume your /api/users endpoint inside a page component:

// pages/users.js
export async function getServerSideProps() {
  const res = await fetch('http://localhost:3000/api/users');
  const users = await res.json();

  return { props: { users } };
}

export default function UsersPage({ users }) {
  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, when a user visits the /users page, getServerSideProps will fetch the list of users from the API before rendering the page. This ensures that the data is already available when the page is loaded.

Step 2: Fetch Data Client-Side with useEffect

You can also consume the API client-side using Reactā€™s useEffect hook. This is useful for fetching data after the page has been loaded.

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

export default function UsersPage() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      const res = await fetch('/api/users');
      const data = await res.json();
      setUsers(data);
    };

    fetchUsers();
  }, []);

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the API request is made after the component is mounted, and the list of users is updated in the componentā€™s state.

Step 3: Make POST Requests to Add Data

To send data to your API, you can use a POST request. Here's an example of how you can send a new userā€™s data to your /api/users endpoint:

import { useState } from 'react';

export default function CreateUser() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    const newUser = { name, email };
    const res = await fetch('/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newUser),
    });

    if (res.ok) {
      alert('User created successfully!');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Create User</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, a new userā€™s name and email are sent to the API as a POST request. Once the request succeeds, an alert is shown.

Conclusion

Next.js makes it incredibly easy to build and consume REST APIs directly within the same framework. By using the API routes feature, you can create serverless endpoints that can handle CRUD operations and integrate them seamlessly with your frontend.

In this post, weā€™ve covered how to create a REST API in Next.js, handle different HTTP methods, and consume that API both server-side (with getServerSideProps) and client-side (using useEffect). This opens up many possibilities for building full-stack applications with minimal configuration.

Next.js continues to empower developers with a flexible and simple solution for building scalable applications with integrated backend functionality. Happy coding!

mongodb Article's
30 articles in total
Favicon
šŸŒ Building Golang RESTful API with Gin, MongoDB šŸŒ±
Favicon
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb
Favicon
Making a Todo API with FastAPI and MongoDB
Favicon
How to Create and Consume a REST API in Next.js
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
Utilizando la librerĆ­a Mongoose
Favicon
Full Stack Development (Mern && Flutter)
Favicon
Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries
Favicon
Comprendre le Design Pattern MVC avec Node.js, Express et MongoDB
Favicon
Set up MongoDB primary and secondary with Docker.
Favicon
The Intricacies of MongoDB Aggregation Pipeline: Challenges and Insights from Implementing It with Go
Favicon
Test Post
Favicon
Containerizing a MERN Stack Application!
Favicon
MongoDB vs. Couchbase: Comparing Mobile Database Features
Favicon
6 Steps to Set Up MongoDB Atlas for Node.js Applications
Favicon
MongoDB: How to setup replica sets
Favicon
To Dockerize a Node.js and MongoDB CRUD app
Favicon
Day 39: Deploying Stateful Applications with StatefulSets (MongoDB)
Favicon
Do you think schema flexibility justifies using NoSQL? Think twice.
Favicon
HadiDB: A Lightweight, Horizontally Scalable Database in Python
Favicon
A Simple Guide for Choosing the Right Database
Favicon
Integrating MongoDB Atlas Alerts with Lark Custom Bot via AWS Lambda
Favicon
šŸ” MongoDB Data Modeling: Embedding vs. Referencing - A Strategic Choice!
Favicon
Unique Index on NULL Values in SQL & NoSQL
Favicon
Embedding vs. Referencing - A Strategic Choice!
Favicon
Series de tiempo en MongoDB
Favicon
I want to write a code for POS sales output interface - and import to mongoDb for sale analysis- however is POS agnostic interface, should work with all POS
Favicon
Hello,help review my fullstack website stack : nestjs,mongodb and reactjs. https://events-org-siiv.vercel.app/
Favicon
Implementing an Express-based REST API in TypeScript with MongoDB, JWT-based Authentication, and RBAC
Favicon
It's a Security Thing.

Featured ones: