How Next js Middleware Works Simple Examples for Authentication SEO and More

Here’s a simple explanation of how middleware works in Next.js, with real-world examples you can use right away.
What is Middleware in Next.js?
Think of middleware as a security guard at the entrance of your website. Every time someone tries to visit a page, the middleware checks their request before letting them in. You can use it to protect pages, redirect visitors, add headers, or even show different content to people in different countries.
Example 1: Protecting Pages with Authentication
Let’s say you want to make sure only logged-in users can see your dashboard. Here’s how you can do it:
Example 2: Show Different Content to Bots (like Google)
Sometimes you want to show a special page to search engines. Here’s how:
Example 3: Redirect Users Based on Country
Want to send people from Germany to a German version of your site? Easy!
Example 4: Clean Up URLs for SEO
Search engines like clean URLs. Here’s how to remove trailing slashes and make URLs lowercase:
Why Use Middleware?
- Protect private pages (like your dashboard)
- Improve SEO by cleaning up URLs or showing special pages to bots
- Show different content based on where someone is visiting from
- Add security headers or other custom logic
Middleware in Next.js is like your website’s bouncer: checking every visitor and making sure they see exactly what you want them to see. It’s simple to set up, and super useful for all kinds of websites!