This is a simple authentication pattern for demo or controlled preview access. It is especially useful for BFSI and other high-security sectors that need restricted preview access before content can be reviewed more broadly.
Problem statement
In some apps, a preview page should not be openly accessible. Editors or reviewers must authenticate before the app loads and renders preview content.What you are doing
You will add a server-side auth check to your preview page. If the request does not have a valid preview session, the page returns401 and shows a login form. After login, the user is redirected back to the preview URL.
This pattern is based on the simple auth flow used in your app:
pages/post/[id].tsxlib/server/post-access-auth.ts- a thin server entry point that sets the cookie
Simple auth logic
The password authentication here is simple:- validate a username and password on the server
- create a signed token for the authenticated user
- store that token in an
HttpOnlycookie - read the cookie in
getServerSideProps - show the login form when the cookie is missing or invalid
lib/server/post-access-auth.ts.
1. Create the auth setup
Keep the auth setup small. The helper should validate credentials, create a signed token, return the cookie value to set, and read the cookie back later ingetServerSideProps.
getPostAccessSession decides whether preview access should be granted.
2. Guard the preview page in getServerSideProps
Read the auth cookie on the server. If the session is missing, return 401 and send the page into login mode.
3. Render the login UI
WhenneedsAuth is true, show a small login form. That form should call a thin server entry point, such as an API route or server action, that uses authenticatePostAccess and sets the returned cookie on the response before redirecting back to requestedPath.
Login form behavior
Keep this logic minimal. The important part is that the form does not set auth state in the browser directly. The server-side auth function produces the cookie, the server sets it on the response, and the next page request reads it.Continue with normal preview rendering
After the user is authenticated, the page follows the same server-side preview flow as the basic preview doc. The auth layer only controls access. It should stay separate from the actual content rendering logic.Core pieces you need
- a server-side credential validator
- a signed auth token
- an
HttpOnlycookie for the preview session - a reusable auth function such as
authenticatePostAccess getServerSidePropsto enforce access on every request- a login UI rendered when access is missing
- redirect back to the requested preview URL after login
Notes
- Keep preview logic server-side.
- Return
401when authentication is required, not200. - Use an
HttpOnlycookie so the browser can send the session automatically on the next request. - Keep the actual content rendering logic separate from the auth layer.