Recent Post:
Categories:
Routing in Next.js is straightforward yet powerful. In this post, we'll delve into dynamic routes, private folders, and encapsulating routes within a single page.
Dynamic routes allow you to create pages with dynamic content based on the URL. This is achieved using brackets in the file names.
// pages/posts/[id].js import { useRouter } from 'next/router'; export async function getStaticPaths() { // Fetch list of posts const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); const paths = posts.map((post) => ({ params: { id: post.id.toString() }, })); return { paths, fallback: false }; } export async function getStaticProps({ params }) { // Fetch individual post data const res = await fetch(`https://api.example.com/posts/${params.id}`); const post = await res.json(); return { props: { post } }; } function Post({ post }) { return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); } export default Post;
In Next.js, there’s no built-in concept of private folders, but you can implement them using authentication checks and middleware.
code
// middleware/auth.js
export default function authMiddleware(req, res, next) {
if (!req.user) {
res.redirect('/login');
} else {
next();
}
}
// pages/protected/dashboard.js
import authMiddleware from '../../middleware/auth';
export default function Dashboard() {
return (
<div>
{' '}
<h1>Protected Dashboard</h1>{' '}
</div>
);
}
export async function getServerSideProps(context) {
await authMiddleware(context.req, context.res);
return { props: {} };
}
You can encapsulate multiple routes in a single page component using conditional rendering based on the route.
code
// pages/admin.js
import { useRouter } from 'next/router';
export default function AdminPage() {
const router = useRouter();
const { section } = router.query;
return (
<div>
<h1>Admin Page</h1>
{section === 'users' && <UsersSection />}
{section === 'settings' && <SettingsSection />}
</div>
);
}
function UsersSection() {
return <div>Manage Users</div>;
}
function SettingsSection() {
return <div>Settings</div>;
}
By leveraging these advanced routing techniques, you can create a flexible and robust navigation structure in your Next.js application.