Building a Full-Stack Application with Next.js API Routes

- Introduction
Next.js is widely known for its powerful capabilities in building static websites, but its ability to handle server-side logic through API routes makes it a perfect candidate for full-stack development. In this blog, we’ll explore how to build a full-stack application using Next.js API routes. You’ll learn how to:
- Set up a Next.js project.
- Create backend API endpoints using Next.js API routes.
- Use these API routes to handle tasks like form submissions, data fetching, and authentication.
- Deploy the entire app to Vercel.
- Why Choose Next.js for Full-Stack Development?
- Full-Stack Capabilities: Next.js allows you to build both frontend (React) and backend (API Routes) within the same project. This makes it simpler to manage code and deploy applications.
- API Routes: Next.js API Routes let you create backend endpoints directly in your Next.js project without needing a separate server (like Express or Fastify). This keeps your stack unified and easy to manage.
- Step-by-Step Guide to Building a Full-Stack Application with Next.js API Routes
-
Setting Up the Project
-
npx create-next-app@latest full-stack-app
cd full-stack-app
- Creating the API Route
- Next.js makes it incredibly easy to create server-side functionality with its API routes. API routes are created inside the pages/api directory and can handle different HTTP methods such as GET, POST, PUT, DELETE, etc.
export default async function handler(req, res) {
if (req.method === 'POST') {
// Extract data from the request body
const { name, email } = req.body;
// Log the data (In a real app, you'd store it in a database)
console.log('Received form submission:', { name, email });
// Send a success response
return res.status(200).json({ message: 'Form submitted successfully!' });
}
// Handle any non-POST request
res.status(405).json({ message: 'Method Not Allowed' });
}
Explanation:
- req: This is the request object, containing the data sent from the client.
- res: This is the response object, which will be sent back to the client.
- req.method: We check if the request is a POST request to handle form submissions
- Building the Front-End Form
import { useState } from 'react'; export default function Home() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); const response = await fetch('/api/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, email }), }); const data = await response.json(); if (response.ok) { setMessage('Form submitted successfully!'); } else { setMessage('Something went wrong. Please try again.'); } }; return ( <div> <h1>Submit Your Details</h1> <form onSubmit={handleSubmit}> <div> <label htmlFor="name">Name:</label> <input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} required /> </div> <div> <label htmlFor="email">Email:</label> <input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} required /> </div> <button type="submit">Submit</button> </form> {message && <p>{message}</p>} </div> ); }
- A form on the front-end where users can input their data.
- An API route on the back-end to handle the data.
- Testing the Full-Stack App
- Check the Console: After submitting the form, open the terminal where you’re running your development server. You should see the data logged there:
Received form submission:
{ name: 'John Doe', email: 'johndoe@example.com' }
- Conclusion
In this blog, we built a simple full-stack application using Next.js API routes. We created a form on the front-end to capture user data, and an API route on the back-end to process and log the submitted data. This is just the beginning — you can extend this setup to integrate with databases, third-party services, authentication, and more.