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
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
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); }
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;
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 </your-password></your-user>
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
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
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); }
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;
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 </your-password></your-user>
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools