Mastering Serverless Functions with Next.js API Routes
Next.js API routes provide an easy and efficient way to build serverless functions directly within your Next.js application. They eliminate the need for separate backend deployments and simplify the development process.
What are Next.js API Routes?
API routes are server-side functions located in the pages/api
directory of your Next.js project. Each file in this directory becomes an API endpoint. When a request is made to that endpoint, the corresponding function is executed on the server.
Creating Your First API Route
Let's create a simple API route that returns a JSON response:
-
Create a file named
pages/api/hello.js
:export default function handler(req, res) { res.status(200).json({ name: 'John Doe' }); }
-
Run your Next.js development server:
npm run dev # or yarn dev # or pnpm dev
-
Access the API route in your browser at
http://localhost:3000/api/hello
. You should see the JSON response:{ "name": "John Doe" }
Handling Different HTTP Methods
You can handle different HTTP methods (GET, POST, PUT, DELETE, etc.) within your API route using req.method
:
export default function handler(req, res) {
if (req.method === 'GET') {
// Handle GET request
res.status(200).json({ message: 'GET request received' });
} else if (req.method === 'POST') {
// Handle POST request
const data = req.body;
res.status(200).json({ message: 'POST request received', data });
} else {
// Handle other methods
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Accessing Request Data
You can access request data through the req
object:
req.query
: Query parameters from the URL.req.body
: The request body (for POST, PUT, etc.).req.cookies
: Cookies sent with the request.req.headers
: Request headers.
Example: Reading Query Parameters
export default function handler(req, res) {
const { name } = req.query;
res.status(200).json({ greeting: `Hello, ${name}!` });
}
Access this route at http://localhost:3000/api/greet?name=Alice
Deploying Serverless Functions
Next.js API routes are automatically deployed as serverless functions when you deploy your Next.js application to platforms like Vercel or Netlify. You don't need to configure any additional serverless infrastructure.
Conclusion
Next.js API routes offer a straightforward and efficient way to build serverless functions directly within your Next.js application. They simplify backend development, reduce infrastructure complexity, and allow you to focus on building amazing user experiences.