🛤️ Next.js Routing Configuration: The Road Manager’s Toolkit
Imagine you’re running a big theme park. Visitors (web requests) arrive at the entrance, and you need to guide them to the right rides. Sometimes you need to send them somewhere else, sometimes you need to secretly move them, and sometimes you need to give them special wristbands. That’s exactly what Next.js routing configuration does for your website!
🎯 The Big Picture
Think of your Next.js app as a magical post office:
- Redirects = “This address moved! Go to the new one!”
- Rewrites = “Secretly deliver mail from one address to another”
- Headers = “Attach special notes to every package”
- Public Folder = “The display shelf everyone can see”
📮 1. Redirects Configuration
What is a Redirect?
A redirect is like a forwarding address. When someone goes to an old page, you send them to a new one—and they see the new address in their browser!
Why Use Redirects?
- You moved a page to a new URL
- You want to fix old broken links
- You’re cleaning up your website structure
How to Set Up Redirects
Open your next.config.js file and add:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
]
},
}
Breaking It Down
| Part | What It Means |
|---|---|
source |
The old address visitors type |
destination |
Where you want to send them |
permanent |
true = moved forever (301), false = temporary (307) |
Real Example: Moving a Blog Post
{
source: '/blog/old-post',
destination: '/articles/new-post',
permanent: true,
}
What happens: Someone visits /blog/old-post → Browser shows /articles/new-post
Using Wildcards (Pattern Matching)
You can redirect many pages at once using special patterns:
{
source: '/blog/:slug',
destination: '/articles/:slug',
permanent: true,
}
Magic! Now /blog/hello goes to /articles/hello, /blog/world goes to /articles/world, and so on!
🎭 2. Rewrites Configuration
What is a Rewrite?
A rewrite is like a secret tunnel. The visitor thinks they’re at one address, but you’re secretly showing them content from another address. The URL in their browser doesn’t change!
Why Use Rewrites?
- Hide your API server’s real address
- Make ugly URLs look pretty
- Connect to external services seamlessly
How to Set Up Rewrites
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
}
Redirect vs Rewrite: The Difference
graph TD A["User visits /old"] --> B{Redirect or Rewrite?} B -->|Redirect| C["Browser URL changes to /new"] B -->|Rewrite| D["Browser URL stays /old"] C --> E["User sees new page"] D --> F["User sees content from /new"]
Real Example: Hiding Your API
{
source: '/api/:path*',
destination: 'https://my-secret-api.com/:path*',
}
What happens:
- User calls
/api/users - They see data from
https://my-secret-api.com/users - But they never know the real server address!
Chaining Rewrites
You can have different types of rewrites:
async rewrites() {
return {
beforeFiles: [
// Runs before pages are checked
],
afterFiles: [
// Runs after pages are checked
],
fallback: [
// Runs only if no page matches
],
}
}
📝 3. Headers Configuration
What are Headers?
Headers are like invisible notes attached to every response your server sends. Browsers read these notes to know how to handle the content.
Why Use Headers?
- Security (stop hackers!)
- Caching (make pages load faster)
- Cross-origin requests (let other websites use your API)
How to Set Up Headers
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY',
},
],
},
]
},
}
Common Security Headers
| Header | What It Does |
|---|---|
X-Frame-Options |
Stops your site from being embedded in iframes |
X-Content-Type-Options |
Prevents browser from guessing file types |
X-XSS-Protection |
Helps block cross-site scripting attacks |
Real Example: Security Headers Bundle
{
source: '/:path*',
headers: [
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
],
}
Adding CORS Headers
Let other websites use your API:
{
source: '/api/:path*',
headers: [
{
key: 'Access-Control-Allow-Origin',
value: '*',
},
{
key: 'Access-Control-Allow-Methods',
value: 'GET, POST, PUT, DELETE',
},
],
}
📁 4. Public Folder
What is the Public Folder?
The public folder is like a shop window. Anything you put there is directly accessible to anyone visiting your website. No processing, no building—just served as-is!
Where is It?
my-next-app/
├── pages/
├── public/ ← This one!
│ ├── favicon.ico
│ ├── images/
│ │ └── logo.png
│ └── robots.txt
└── next.config.js
What Goes in Public?
- Images (logos, icons, photos)
- Fonts (custom typography)
- favicon.ico (browser tab icon)
- robots.txt (search engine instructions)
- sitemap.xml (page listing for search engines)
How to Use Public Files
Files in public are accessed from the root URL:
| File Location | URL to Access |
|---|---|
public/logo.png |
/logo.png |
public/images/cat.jpg |
/images/cat.jpg |
public/fonts/custom.woff2 |
/fonts/custom.woff2 |
Real Example: Using an Image
// In your React component
function Header() {
return (
<img
src="/logo.png"
alt="My Logo"
/>
)
}
Important Rules
- No
/publicin the URL - Just use/logo.png, not/public/logo.png - Files are served as-is - No processing or optimization
- Case-sensitive -
/Logo.pngand/logo.pngare different! - Static only - Can’t use dynamic routes here
🎪 Putting It All Together
Here’s a complete next.config.js with all four features:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-blog/:slug',
destination: '/blog/:slug',
permanent: true,
},
]
},
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.myapp.com/:path*',
},
]
},
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY',
},
],
},
]
},
}
And your public folder:
public/
├── favicon.ico
├── robots.txt
└── images/
└── logo.png
🧠 Quick Memory Trick
Think of a restaurant:
- Redirects = “That table moved! Go to table 5 instead!”
- Rewrites = “Stay at table 3, but I’ll bring you food from the kitchen (you don’t need to know which chef made it)”
- Headers = “Here’s your food + a note saying ‘contains nuts’”
- Public = “The menu on the wall—anyone can see it!”
✅ You Did It!
Now you understand the four pillars of Next.js routing configuration:
- Redirects - Send visitors to new addresses
- Rewrites - Secret content tunnels
- Headers - Invisible security notes
- Public Folder - Your shop window
You’re ready to build smarter, safer, and more organized Next.js applications!
