Next.js App Router Code Sample: Basic Authentication

This Next.js code sample demonstrates how to implement web application authentication using the Auth0 Next.js SDK and the Next.js App Router that leverages React’s latest features.

I’m using a parallel route (Nextjs App router) to render slots in my layout based on user authentication state .
How can I Check whether the user is logged in or not in the top level of my default export layout function in layout.js ?

Hi @jaatinc, how are you?

I’m assuming you are using the Auth0 NextJS SDK, right? When using the Auth0 NextJS SDK, you’ll need to wrap the root or parent layout component with the UserProvider component, here is an example:

// app/layout.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export default function App({ children }) {
  return (
    <UserProvider>
      <body>{children}</body>
    </UserProvider>
  );
}

In the same layout component, as long as you place components in the UserProvider, you can access the useUser hook to get information about the user and session.

Just note, that any component using useUser needs to be marked as a client component with the directive use client at the top of the file, eg:

// components/user.js
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';

export default function User() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  if (user) {
    return (
      <div>
        Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
      </div>
    );
  }

  return <a href="/api/auth/login">Login</a>;
}

Does that help your use case?

1 Like