How to Create Routes in Next.js: Simple Guide
In Next.js, you create routes by adding files inside the
pages folder; each file automatically becomes a route. For dynamic routes, use square brackets like [id].js to capture URL parameters.Syntax
Next.js uses the pages folder to define routes automatically. Each file inside this folder corresponds to a route path. Dynamic routes use square brackets to capture variables from the URL.
pages/index.js→/(home page)pages/about.js→/aboutpages/blog/[id].js→/blog/:idwhere:idis dynamic
plaintext
pages/ index.js // route: / about.js // route: /about blog/ [id].js // route: /blog/:id (dynamic route)
Example
This example shows a simple Next.js app with a home page, an about page, and a dynamic blog post page that shows the post ID from the URL.
javascript
/* pages/index.js */ export default function Home() { return <h1>Home Page</h1>; } /* pages/about.js */ export default function About() { return <h1>About Page</h1>; } /* pages/blog/[id].js */ import { useRouter } from 'next/router'; export default function BlogPost() { const router = useRouter(); const { id } = router.query; return <h1>Blog Post ID: {id}</h1>; }
Output
Visiting / shows "Home Page"; /about shows "About Page"; /blog/123 shows "Blog Post ID: 123"
Common Pitfalls
Common mistakes when creating routes in Next.js include:
- Placing files outside the
pagesfolder, so routes don't work. - Forgetting to use square brackets for dynamic routes, causing static routes instead.
- Using uppercase letters in filenames, which can cause routing issues on some systems.
- Not handling the case when
router.queryis empty on first render in dynamic routes.
javascript
/* Wrong: dynamic route without brackets - this creates a static route named 'id.js' */ // pages/blog/id.js export default function BlogPost() { return <h1>This is not dynamic</h1>; } /* Right: dynamic route with brackets */ // pages/blog/[id].js import { useRouter } from 'next/router'; export default function BlogPost() { const router = useRouter(); const { id } = router.query; return <h1>Blog Post ID: {id}</h1>; }
Quick Reference
Summary tips for creating routes in Next.js:
- Put your page files inside the
pagesfolder. - Use
index.jsfor the home route/. - Use file names to match route paths (e.g.,
about.js→/about). - Use square brackets for dynamic routes (e.g.,
[id].js). - Access dynamic params with
useRouter().query.
Key Takeaways
Routes in Next.js are created by adding files inside the pages folder.
Dynamic routes use square brackets in filenames to capture URL parameters.
Each file name corresponds directly to a route path in the app.
Use useRouter().query to access dynamic route parameters inside components.
Always place route files inside the pages folder for Next.js to recognize them.