JS
Next.js
What is Next.js?
Next.js is an open-source React front-end development web framework that enables functionality such as server-side rendering and generating static websites for React-based web applications.
Create an App
> npx create-next-app@latest <app_name>
Create API Routes
API Routes let you create an API endpoint inside a Next.js app. You can do so by creating a function inside the pages/api
directory that has the following format:
// req = HTTP incoming message, res = HTTP server response
export default function handler(req, res) {
// ...
}
Learn more about the request handler above in the API Routes documentation.
They can be deployed as Serverless Functions (also known as Lambdas).
Creating a simple API endpoint
Let’s try it out. Create a file called hello.js
in pages/api
with the following code:
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' });
}
Try accessing it at http://localhost:3000/api/hello
. You should see {"text":"Hello"}
. Note that:
req
is an instance ofhttp.IncomingMessage
, plus some pre-built middlewares.res
is an instance ofhttp.ServerResponse
, plus some helper functions.
That’s it! Before we wrap up this lesson, let’s talk about some tips for using API Routes
on the next page.
App Router
In a Next.js project using the App Router (app/ folder), you might see folders named [id] inside the app/ directory. These are Dynamic Route Segments, and they are used to create dynamic routes where part of the URL is a variable.
What Does [id] Mean?
- The [id] folder is a dynamic segment, meaning it can match any value in that part of the URL.
- n a user visits /products/123, the [id] folder handles the request, and page.tsx inside it will receive { id: "123" } as a dynamic parameter.
How to Use It in a Page?
In app/products/[id]/page.tsx
, you can retrieve the dynamic id parameter using:
import { useParams } from 'next/navigation';
export default function ProductPage() {
const params = useParams();
const productId = params.id; // Dynamic segment from URL
return <h1>Product ID: {productId}</h1>;
}
Or using Server Components
(recommended in the App Router):
import { notFound } from 'next/navigation';
export default function ProductPage({ params }: { params: { id: string } }) {
if (!params.id) return notFound(); // Handle missing ID gracefully
return <h1>Product ID: {params.id}</h1>;
}
Nested Dynamic Routes
You can also nest dynamic segments:
- app
- products
- [id]
- reviews
- [review_id]
- page.tsx
- [review_id]
- reviews
- [id]
- products
This would match URLs like:
/products/123/reviews/456
page/[id]/page.tsx
When you need to retrieve dynamic parameters from the URL, you can use the following code:
type Params = Promise<{ id: string }>
export default async function ExampleDetailsPage(props: { params: Params }) {
const params = await props.params;
const id = params.id;
}
Client Side:
"use client";
import { use } from 'react';
type Params = Promise<{ id: string }>
export default function ExampleDetailsPage(props: { params: Params }) {
const params = use(props.params);
const id = params.id;
}