Next.js is an excellent framework for building web applications,
allowing developers to create both frontend and backend functionalities
within the same codebase. One of its standout features is API Routes,
which lets you build your backend directly into your Next.js
application. This guide will explore how to leverage API routes in
Next.js for full-stack development using both the App Router and Page Router, making your application more efficient and cohesive.
Why?
- Single Codebase for all your codebase
- No cors issues, single domain name for your FE and BE
- Ease of deployment, deploy a single codebase
What Are API Routes?
API routes are a way to create RESTful endpoints in your Next.js
application. They allow you to handle requests, manage data, and
communicate with databases or other external services directly from your
Next.js application. Think of them as server-side functions that
respond to HTTP requests (like GET, POST, PUT, DELETE) and serve as the
backbone for your app’s data management
Let’s try to build this
Create an empty nextjs project
npx create-next-app@latest ./
- Clean up
page.tsx
,global.css
- Create a new folder named
api
- Inside this folder, add another folder named
auth
- Create a file called
route.ts
within theauth
folder
Define a simple
GET
route inside route.ts
as follows:export async function GET(){ return Response.json({name:"tushar",message:"hello"}); }
Make a api call in page.tsx to hit this URL
import axios from "axios"; async function getUserDetails() { try { const response = await axios.get("http://localhost:3000/api/auth") return response.data; } catch(e) { console.log(e); } } export default async function Home() { const userData = await getUserDetails(); return ( <div> {userData.name} {userData.message} </div> ); }