dev-resources.site
for different kinds of informations.
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
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: "[email protected]" },
{ id: 2, name: "Jane Smith", email: "[email protected]" },
];
// 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.
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;
}
}
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
}
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>
);
}
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>
);
}
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>
);
}
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!
Featured ones: