← Back
Author Avatar

@Tushar-tech7

Published: November 25, 2024

77 Views

Backend in Nextjs

Backend in Nextjs
WebDevelopment

Backend in Nextjs

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?

  1. Single Codebase for all your codebase
  1. No cors issues, single domain name for your FE and BE
  1. 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 ./
  1. Clean up page.tsx, global.css
  1. Create a new folder named api
  1. Inside this folder, add another folder named auth
  1. Create a file called route.ts within the auth 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> ); }
 

© 2024 Tushar Agarwal. All rights reserved.
Made with By Tushar Agarwal