NextJS Route

Ramkumar Khubchandani
2 min readJan 10, 2024

--

1. File-System Based Routing:

  • Structure Reflects Routes: In Next.js, the structure of your pages directory directly maps to the routes of your application. Each file inside pages becomes a route, and nested folders create nested routes.
pages/
index.js -> /
about.js -> /about
posts/
first-post.js -> /posts/first-post

2. Creating Pages:

  • Simply create a file: To create a new route, simply create a new file with the desired route name within the pages directory.
// pages/about.js
function About() {
return <h1>This is the About page</h1>;
}

export default About;

3. Dynamic Routes:

  • Square Brackets: Use square brackets [] to define dynamic segments in a file name.
  • Access Parameters: Access the dynamic parameter values using the useRouter hook.

Example:

pages/posts/[id].js -> /posts/1, /posts/hello-world, etc

// pages/posts/[id].js
import { useRouter } from 'next/router';

function Post() {
const router = useRouter();
const { id } = router.query;

return <h1>Post with ID: {id}</h1>;
}

export default Post;

4. Linking and Navigation:

  • Link Component: Use the Link component from Next.js for client-side navigation, ensuring a smooth user experience.
  • useRouter Hook: Access the router object for programmatic navigation and other routing-related actions.
  • Example:
import Link from 'next/link';

function Home() {
return (
<div>
<Link href="/about">About</Link>
<Link href="/posts/1">Post 1</Link>
</div>
);
}

5. API Routes:

  • For Server-Side Logic: Create API routes within a pages/api directory to handle server-side logic, data fetching, and database interactions.
  • Example:
pages/api/hello.js
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js API route!' });
}

Additional Points:

  • Custom App: Override the default app component to control page initialization, loading states, and global layout.
  • Custom Document: Extend the default Document component to customize the HTML structure of your pages.
  • Prefetching and Caching: Next.js automatically prefetches and caches routes for a smoother user experience.

Do you want to learn more like this ?

Follow me or message me on Linkedin.

--

--

Ramkumar Khubchandani
Ramkumar Khubchandani

Written by Ramkumar Khubchandani

Frontend Developer|Technical Content Writer|React|Angular|React-Native|Corporate Trainer|JavaScript|Trainer|Teacher| Mobile: 7709330265|ramkumarkhub@gmail.com

No responses yet