Time‑Based Public Access for the `/tv` Route in a Next.js App

2026年8月30日2 次浏览来源:Dev.to阅读原文

Time‑Based Public Access for the Route in a Next.js App TL;DR: I added a temporal gate that lets anyone hit 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 and and required proper timezone handling and a tiny refactor of the auth flow.

The Problem Our TV dashboard () 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 () forced a session cookie () on all routes, including .

The result was a “401 Unauthorized” on the lobby screen after 6 pm, which broke the intended user experience.

The symptom was simple: 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 path and only during the defined business hours.

What I Tried First My first instinct was to add a quick 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 () 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 , 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 in .

It receives a start hour, an end hour, and a timezone identifier, then returns a boolean indicating whether the current moment falls inside that window.

I opted for because it’s a lightweight, tree‑shakable way to handle timezones without the overhead of Moment.

The function is deliberately pure, making it easy to unit‑test.

2.

Extend the auth flow The existing function stayed untouched, but I added a comment block to indicate the temporary nature of the change (as seen in the diff).

The real work happened in .

Key points: Path check first – By handling the shortcut before any cookie logic, we avoid unnecessary async work.

Time window – matches the requirement exactly: inclusive of 9 am, exclusive of 6 pm.

Fallback – Outside the window, the request proceeds through the normal token validation, preserving security for after‑hours.

3.

Adjust the diff for completeness The commit diff showed only the addition of a comment line in .

I expanded it to the full helper function above.

The middleware diff added the import of and the conditional block.

The final diff looks like this:

4.

Test locally I added a quick unit test for :

分享