
Functions in NextJS
⚡ Functions in Next.js
Next.js provides various built-in functions that help with data fetching, API handling, routing, and rendering.
📌 1. Data Fetching Functions
🔹 getStaticProps
(Static Generation - SSG)
Fetches data at build time and caches it.
export async function getServerSideProps() { const res = await fetch("https://api.example.com/data"); const data = await res.json(); return { props: { data } };}
✅ Best for user-specific content (e.g., dashboards)
🔹 getStaticPaths
(Dynamic Static Generation)
Pre-generates dynamic routes using getStaticProps
.
export async function getStaticPaths() { const res = await fetch("https://api.example.com/posts"); const posts = await res.json(); const paths = posts.map((post) => ({ export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js API!" });}
✅ Acts as a backend function in Next.js
🔹 Handling POST Requests
export default function handler(req, res) { if (req.method === "POST") { res.status(200).json({ message: `Received: ${req.body.name}` }); } else { res.status(405).json({ message: "Method Not Allowed" }); }}
✅ Handles dynamic API requests
📌 3. Middleware Functions
Middleware functions intercept requests before they reach a route.
import { NextResponse } from "next/server";export function middleware(req) { if (!req.cookies.token) { return NextResponse.redirect("/login"); }}
✅ Useful for authentication and logging
📌 4. Client-Side Utility Functions
You can create reusable utility functions for components.
🔹 Formatting Date Utility
export function formatDate(date) { return new Date(date).toLocaleDateString();}
✅ Helps keep components clean
📌 5. Best Practices
✔️ Use getStaticProps
when possible for better performance
✔️ Use API routes instead of exposing backend logic in components
✔️ Keep functions modular for reusability