Next.js is a powerful React framework that enables full-stack development by seamlessly integrating frontend and backend capabilities. With built-in API routes, developers can create server-side logic without needing an external backend service. This makes Next.js an ideal choice for modern web applications.
In this article, we will cover:
- Setting up Next.js for full-stack development
- Creating API routes with server-side logic
- Deploying locally with Node.js and Vercel CLI
By the end of this guide, you will have a fully functional Next.js app running locally with API routes.
1. Setting Up Next.js for Full-Stack Development
1.1 Installing Next.js
To get started, install Next.js using the following command:
npx create-next-app@latest my-next-app
cd my-next-app
Alternatively, use Yarn:
yarn create next-app my-next-app
cd my-next-app
This command scaffolds a Next.js project with all necessary dependencies.
1.2 Project Structure
Once installed, your project will have the following structure:
my-next-app/
├── pages/
│ ├── index.js (Home Page)
│ ├── api/
│ │ ├── hello.js (Example API Route)
├── public/
├── styles/
├── package.json
├── next.config.js
The pages/api/ directory is where API routes are defined.
2. Creating API Routes with Server-Side Logic
2.1 Understanding API Routes
Next.js API routes enable backend logic within the same application. Any file inside pages/api/
is mapped to /api/*
and is treated as a serverless function.
2.2 Creating an API Endpoint
Create a new API route in pages/api/greet.js
:
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ message: 'Hello from Next.js API!' });
} else {
res.status(405).json({ error: 'Method Not Allowed' });
}
}
2.3 Consuming API Routes
You can fetch this API route in a frontend component:
import { useEffect, useState } from 'react';
export default function Home() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/greet')
.then(response => response.json())
.then(data => setData(data.message));
}, []);
return <div>{data ? data : 'Loading...'}</div>;
}
3. Deploying Locally with Node.js and Vercel CLI
3.1 Running Locally with Node.js
To start the Next.js development server, run:
npm run dev
or with Yarn:
yarn dev
The application will be available at http://localhost:3000
.
3.2 Deploying Locally with Vercel CLI
Install Vercel CLI globally:
npm install -g vercel
Login to Vercel:
vercel login
Deploy the project locally:
vercel dev
This allows you to test your full-stack application with server-side API routes in a production-like environment.
Conclusion
In this article, we implemented a Next.js full-stack application by:
- Setting up Next.js for frontend and backend development
- Creating API routes to handle backend logic
- Deploying and running the application locally using Node.js and Vercel CLI
With this setup, you can efficiently develop, test, and deploy Next.js applications with built-in API capabilities.