In Next.js 13, the
app
directory represents different pages of your website.Inside the
app
directory, each folder corresponds to a different page of your website.Within each folder, you can create a
page.js
orpage.jsx
file to hold your markup logic (html) for that page.
Routing
Defining Routes
Routes are automatically created based on the file structure in the
app
directory.For example, if you have a folder named
about
with apage.jsx
file, it will be accessible at/about
.Nested folders represent nested routes, like
/about/team
for a nestedteam
route.
Dynamic Routes
You can create dynamic routes using brackets, e.g.,
[slug]
.For example, a folder named
[slug]
can handle URLs like/posts/1
or/users/42
.
Query Parameters
Query parameters can be used with the
useRouter
hook.Import
useRouter
fromnext/router
and use thequery
object.For example, for
/search?q=nextjs
,query.q
will be'nextjs'
.
Links and Navigation
To navigate between pages, use the
Link
component fromnext/link
.Wrap your anchor tags with
Link
to prevent full-page reloads.
import Link from 'next/link';
<Link href="/about">
<a>About Us</a>
</Link>
API Routes
API Directory Structure
For APIs, create an
api
directory inside the app directory.Inside
api
, create folders representing different API endpoints.
API Routing
The API route URL is constructed based on the folder and file structure.
For example,
/api/posts/route.js
is accessible at/api/posts
.API routes do not create static files; they're handled by the server.
Introduction to Dynamic Api Routing in Next.js 13: A Brief Overview
Dynamic routing in Next.js 13 offers a powerful way to handle variable segments in URLs, enabling the creation of flexible and personalized user experiences. Instead of having separate routes for every unique parameter, dynamic routing allows you to handle various cases with a single route handler. This approach is particularly valuable when dealing with content that requires variable identification, such as blog posts, product pages, or user profiles.
Setting Up Dynamic Routes In The Api Folder: The Basics
To create dynamic API routes in Next.js 13, utilize the folder structure within the app
directory. For instance, to handle dynamic blog posts, create an api
folder first. You can then create [id]
folder inside app/api/posts
. Inside the [id]
folder, you can create a route.js
file to define the logic for fetching, updating, and deleting blog posts based on their IDs.
Example 1: Fetching and Manipulating Data by ID
// app/posts/[id]/route.js
import DB from '@/app/lib/utils/dbHelper';
import { NextResponse } from 'next/server';
// Fetching a Blog Post by ID
export async function GET(request, context) {
try {
const { id } = context.params;
const result = await DB.executeProcedure('getOneBlog', { id });
if (result.recordset.length > 0) {
const blog = result.recordset[0];
return NextResponse.json(blog, { status: 200 });
} else {
return NextResponse.json({ message: 'Blog not found' });
}
} catch (error) {
console.log(error);
}
}
// Updating a Blog Post by ID
export async function PUT(request, context) {
try {
const { id } = context.params;
const requestBody = await request.json();
const blogDetails = { ...requestBody, id };
const result = await DB.executeProcedure('updateBlog', blogDetails);
if (result.rowsAffected[0] > 0) {
return NextResponse.json({ message: 'Blog updated successfully' });
} else {
return NextResponse.json({ message: 'Blog not found' });
}
} catch (error) {
console.log(error);
}
}
// Deleting a Blog Post by ID
export async function DELETE(request, context) {
try {
const { id } = context.params;
const result = await DB.executeProcedure('deleteBlog', { id });
if (result.rowsAffected[0] > 0) {
return NextResponse.json({ message: 'Blog deleted successfully' });
} else {
return NextResponse.json({ message: 'Blog not found' });
}
} catch (error) {
console.log(error);
return NextResponse.json({ message: 'Server Error' });
}
}
In this example, the [id]
folder represents dynamic routing where the id
is a dynamic segment in the URL. Each HTTP method (GET
, PUT
, DELETE
) corresponds to a specific API action (fetching, updating, deleting) for a blog with a particular ID. The context.params
object is used to extract the dynamic id
from the URL.
In the above examples, we've demonstrated how to handle dynamic routing in Next.js 13 for both user-friendly URLs and custom API endpoints. By harnessing the power of dynamic routing, you can streamline your codebase, enhance user experiences, and build sophisticated applications with ease. Stay tuned for more in-depth insights into Next.js 13 as we continue to explore its cutting-edge features and capabilities. Happy coding!