Next.js: restrict pages to authenticated users

Many websites have pages that need to be restricted to authenticated users, for example profile pages or dashboards.

Next.js web framework comes with a lot of functionality built-in JS compilation, rendering code on server and caching.
When it comes to most other aspecs, it's up to a programmer to build, including such needed functionality as restricting access to some pages only to authenticated users.

In this article we are going to build just that: a function that augments a page object, that could be used like that:

Here's the implementation in TypeScript:

In order to make it work on server we are going to need one more utility function fetchWithCookies.
When making HTTP request from inside a Web Browser, the browser automatically sends cookies with each requests and then stores new cookies if a response comes in with set-cookie header.
On server-side we need to build this feature ourselves, because neither Next.js nor NodeJS make any assumption about a request flow.
In order to do that we can leverage ctx: { req, res } object that Next.js passes into getInitialProps during SSR.

Of course this implementation is only one way to do this, for example the HTTP client looks different if you are using Apollo Graphql.

Thank you for reading!

Popular posts from this blog

HTTP server in Ruby 3 - Fibers & Ractors

Using image loader is Next.js