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.
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.
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.
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
If you’re using MongoDB Atlas, you can get this URI from the Atlas dashboard.
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.
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:
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
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.
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.
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.
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
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.
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!