Recent Post:
Categories:
Next.js provides a powerful way to create API routes that reside alongside your pages, simplifying the development of full-stack applications. Let's explore how to set up and use API routes effectively.
API routes in Next.js are created inside the pages/api directory. Each file in this directory corresponds to an API endpoint.
code
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello, world!' });
}
You can handle different HTTP methods within a single API route by checking req.method.
code
// pages/api/users.js
export default function handler(req, res) {
if (req.method === 'GET') {
// Handle GET request
res.status(200).json({ users: ['User1', 'User2'] });
} else if (req.method === 'POST') {
// Handle POST request
const newUser = req.body;
res.status(201).json({ user: newUser });
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
You can connect to a database within your API routes to fetch or manipulate data.
code
// pages/api/posts.js
import { connectToDatabase } from '../../lib/db';
export default async function handler(req, res) {
const db = await connectToDatabase();
if (req.method === 'GET') {
const posts = await db.collection('posts').find().toArray();
res.status(200).json(posts);
} else if (req.method === 'POST') {
const newPost = req.body;
await db.collection('posts').insertOne(newPost);
res.status(201).json(newPost);
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Using API routes in Next.js simplifies the process of creating backend functionality and integrating it seamlessly with your frontend.