𝗡𝗲𝘅𝘁.𝗷𝘀 𝗥𝗼𝘂𝘁𝗲 𝗣𝗿𝗼𝘁𝗲𝗰𝘁𝗶𝗼𝗻 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗟𝗶𝗯𝗿𝗮𝗿𝗶𝗲𝘀
Most think you need NextAuth or Clerk for route protection. You do not. Small projects only need a cookie check.
Next.js middleware runs before requests hit your page. It checks access.
- No login? Go home.
- Login? Go to dashboard.
- Check: The isLoggedIn cookie.
Create middleware.ts in your root folder. Use a matcher. Matchers stop slow loads on images and API routes.
Set the isLoggedIn cookie to true to log in. Set it to a past date to log out.
Warning: This is not for real data. Users edit cookies in DevTools. Use signed JWTs for production. Use this for speed.
No installs. Copy. Paste. Ship.
Source: https://dev.to/abdulrdeveloper/nextjs-middleware-route-protection-without-any-library-7ec