Protected routes with middleware
📖 Scenario: You are building a Next.js app that has some pages only accessible to logged-in users. To keep your app safe, you want to block visitors who are not logged in from seeing these pages.Middleware in Next.js can help by checking if a user is logged in before letting them visit protected pages.
🎯 Goal: Build a simple Next.js middleware that checks if a user is logged in by looking for a cookie called token. If the cookie is missing, the user is redirected to the login page. Otherwise, they can access the protected page.
📋 What You'll Learn
Create a middleware file in the root of the Next.js app
Check for a cookie named
token in the requestRedirect users without the
token cookie to /loginAllow users with the
token cookie to continue to the requested pageApply middleware only to the
/dashboard route💡 Why This Matters
🌍 Real World
Middleware is used in real apps to protect pages that require login, like dashboards or user profiles.
💼 Career
Understanding middleware and route protection is important for building secure web applications and is a common task in frontend and full-stack developer roles.
Progress0 / 4 steps