Authentication

Authentication verifies who a user is, while authorization controls what a user can access. Next.js supports multiple authentication patterns, each designed for different use cases. This page will go through each case so that you can choose based on your constraints.

Authentication Patterns

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

  • Use static generation to server-render a loading state, followed by fetching user data client-side.
  • Fetch user data server-side to eliminate a flash of unauthenticated content.

Authenticating Statically Generated Pages

Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of getServerSideProps and getInitialProps 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 next/link. 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:

  1. // pages/profile.js
  2. import useUser from '../lib/useUser'
  3. import Layout from '../components/Layout'
  4. const Profile = () => {
  5. // Fetch the user client-side
  6. const { user } = useUser({ redirectTo: '/login' })
  7. // Server-render loading state
  8. if (!user || user.isLoggedIn === false) {
  9. return <Layout>Loading...</Layout>
  10. }
  11. // Once the user request finishes, show the user
  12. return (
  13. <Layout>
  14. <h1>Your Profile</h1>
  15. <pre>{JSON.stringify(user, null, 2)}</pre>
  16. </Layout>
  17. )
  18. }
  19. export default Profile

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

Authenticating Server-Rendered Pages

If you export an async function called getServerSideProps from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

  1. export async function getServerSideProps(context) {
  2. return {
  3. props: {}, // Will be passed to the page component as props
  4. }
  5. }

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

  1. // pages/profile.js
  2. import withSession from '../lib/session'
  3. import Layout from '../components/Layout'
  4. export const getServerSideProps = withSession(async function ({ req, res }) {
  5. const { user } = req.session
  6. if (!user) {
  7. return {
  8. redirect: {
  9. destination: '/login',
  10. permanent: false,
  11. },
  12. }
  13. }
  14. return {
  15. props: { user },
  16. }
  17. })
  18. const Profile = ({ user }) => {
  19. // Show the user. No loading state is required
  20. return (
  21. <Layout>
  22. <h1>Your Profile</h1>
  23. <pre>{JSON.stringify(user, null, 2)}</pre>
  24. </Layout>
  25. )
  26. }
  27. export default Profile

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 static generation.

Authentication Providers

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

Bring Your Own Database

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 next-auth.

Both of these libraries support either authentication pattern. If you’re interested in Passport, we also have examples for it using secure and encrypted cookies:

Other Providers

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

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.

Data FetchingLearn more about data fetching in Next.js.