Home Web Front-end JS Tutorial How to Create and Consume a REST API in Next.js

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

Jan 13, 2025 pm 02:31 PM

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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: "john@example.com" },
    { id: 2, name: "Jane Smith", email: "jane@example.com" },
  ];

  // Send the list of users as a JSON response
  res.status(200).json(users);
}
Copy after login
Copy after login

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;
Copy after login
Copy after login

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
Copy after login
Copy after login

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.

npx create-next-app my-next-api-project
cd my-next-api-project
npm install mongodb
npm run dev
Copy after login
Copy after login

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:

mkdir pages/api
touch pages/api/users.js
Copy after login
Copy after login

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/api/users.js
export default function handler(req, res) {
  // Define a list of users
  const users = [
    { id: 1, name: "John Doe", email: "john@example.com" },
    { id: 2, name: "Jane Smith", email: "jane@example.com" },
  ];

  // Send the list of users as a JSON response
  res.status(200).json(users);
}
Copy after login
Copy after login

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.

// 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;
Copy after login
Copy after login

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:

# .env.local
MONGODB_URI=mongodb+srv://<your-user>:<your-password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
Copy after login
Copy after login

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!

The above is the detailed content of How to Create and Consume a REST API in Next.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1241
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles