Authentication

    The first step to identifying which authentication pattern you need is understanding the you want. We can then determine which authentication providers support this strategy. There are two main patterns:

    • Fetch user data server-side to eliminate a flash of unauthenticated content.

    Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of getServerSideProps and in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side.

    One advantage of this pattern is it allows pages to be served from a global CDN and preloaded using . In practice, this results in a faster TTI (Time to Interactive).

    Let’s look at an example for a profile page. This will initially render a loading skeleton. Once the request for a user has finished, it will show the user’s name:

    You can view this . Check out the with-iron-session example to see how it works.

    Let’s transform the profile example to use server-side rendering. If there’s a session, return user as a prop to the component in the page. Notice there is not a loading skeleton in .

    An advantage of this pattern is preventing a flash of unauthenticated content before redirecting. It’s important to note fetching user data in getServerSideProps will block rendering until the request to your authentication provider resolves. To prevent creating a bottleneck and increasing your TTFB (Time to First Byte), you should ensure your authentication lookup is fast. Otherwise, consider .

    Now that we’ve discussed authentication patterns, let’s look at specific providers and explore how they’re used with Next.js.

    Examples

    If you have an existing database with user data, you’ll likely want to utilize an open-source solution that’s provider agnostic.

    • If you want a low-level, encrypted, and stateless session utility use iron-session.
    • If you want a full-featured authentication system with built-in providers (Google, Facebook, GitHub…), JWT, JWE, email/password, magic links and more… use .

    To see examples with other authentication providers, check out the .

    Examples

    For more information on what to do next, we recommend the following sections:

    PagesLearn more about pages and the different pre-rendering methods in Next.js.