How to create an API in Next.js


Next.js, an advanced React framework, streamlines web application development with features like server-side rendering and automatic code splitting. Creating APIs in Next.js is advantageous due to its built-in API routes feature, offering a seamless and integrated approach for handling server-side logic or connecting to databases. This simplifies the development process, ensuring efficient communication between the frontend and backend within the same framework.

Route Handlers allow you to create custom APIs.

Note: Route Handlers are only available inside the app directory. 

Route Handlers are defined in a route.js|ts file inside the app directory.

app/api/route.ts

export const dynamic = 'force-dynamic' // defaults to auto
export async function GET(request: Request) {}
Supported HTTP Methods are: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.

Example:
export async function GET() {  
const res = await fetch('https://data.mongodb-api.com/...', {    
headers: {      
'Content-Type': 'application/json',      
'API-Key': process.env.DATA_API_KEY,    
},  
})  
const data = await res.json()   
return Response.json({ data })
}

Comments

Popular posts from this blog

Host Your Node.js App on AWS EC2 Instance for Free in 2024

GitCommandsPro Your Guide to Essential Git Commands in 2024

SOAP Explained: With Javascript