Time‑Based Public Access for the `/tv` Route in a Next.js App
Time‑Based Public Access for the /tv Route in a Next.js App TL;DR: I added a temporal gate that lets anyone hit /tv without a session cookie between 9 am‑6 pm America/Cancun. Outside that window the request falls back to the normal auth middleware. The change lives in src/lib/auth.ts and src/middleware.ts and required proper timezone handling and a tiny refactor of the auth flow. The Problem Our TV dashboard ( /tv ) is meant to be displayed on a wall screen in the office lobby. The screen should be visible to anyone during office hours, but it must stay protected after hours. The original middleware ( src/middleware.ts ) forced a session cookie ( AUTH_COOKIE_NAME ) on all routes, including /tv . The result was a “401 Unauthorized” on the lobby screen after 6 pm, which broke the intended user experience. The symptom was simple: GET /tv → 401 Unauthorized The error came from the auth middleware that blindly redirected unauthenticated requests to the login page. We needed a conditional bypass that only applied to the /tv path and only during the defined business hours. What I Tried First My first instinct was to add a quick if (request.nextUrl.pathname === "/tv") return NextResponse.next(); at the top of the middleware. That let the request pass, but it also opened the route for the whole day, ignoring the time constraint. I tried to read the server’s local time ( new Date() ) and compare the hour, but the server runs on UTC, so the check was off by 5 hours for the America/Cancun zone. The result was that the route was either always open or always closed, depending on where the CI runner was located. I also considered using a third‑party library like moment-timezone , but pulling in a heavy dependency for a single hour check felt overkill. The Implementation 1. Add a tiny time‑window helper I created a pure function isWithin in src/lib/auth.ts . It receives a start hour, an end hour, and a timezone identifier, then returns a boolean indicating whether the current momen