logo

SINGULARITY

DOCS

PurchaseReturn to the Dashboard

Authentication in Singularity React with Next.js App Router

Singularity React leverages Auth.js (previously NextAuth.js) for managing authentication, seamlessly integrated with Next.js 13's App Router. Auth.js offers a comprehensive, open-source solution for authentication, designed to work effortlessly with Next.js applications.

Key Features of Auth.js with App Router
  • Seamless integration with Next.js 13 App Router
  • Support for OAuth providers and custom credentials
  • Server-side session management
  • Built-in CSRF protection
  • TypeScript support
Configuration

The Auth.js configuration file is located at @auth/authjs.ts.

You can incorporate providers such as Facebook, GitHub, Twitter, and others. Refer to the Auth.js documentation for further details.

Below is a sample configuration for integrating a Google login provider:

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    // Include additional providers here
  ],
  // Insert custom configuration options here
})

export { handler as GET, handler as POST }
Custom Session Handling

In Singularity React, we’ve enhanced Auth.js’s default session handling to include additional user data. Upon login, we retrieve extra user information from an API and incorporate it into the session, enabling easy access to detailed user data across the application.

This is how it’s implemented in the authJs.ts file:

// src/@auth/authJs.ts
// ... other imports and configurations ...

const config = {
  // ... other config options ...
  callbacks: {
    async session({ session, token }) {
      if (token.accessToken && typeof token.accessToken === 'string') {
        session.accessToken = token.accessToken;
      }

      if (session && token.sub && typeof token.sub === 'string') {
        const userId = token.sub;
        const userDbData = await fetchUserData(userId, session);
        session.db = userDbData || null;
      }

      return session;
    }
  },
  // ... other config options ...
};

async function fetchUserData(userId: string, session: Session): Promise<User | null> {
  // Retrieve user data from the API or create a new user if not found
  // ... implementation details ...
}

// Expand the Session type to include custom properties
declare module 'next-auth' {
  interface Session {
    accessToken?: string;
    db: User;
  }
}

This customized session handling enables storage of additional user details, such as roles, settings, or other custom attributes, making them readily accessible throughout the application.

useUser Hook

Singularity React includes a custom useUser hook to streamline access to user data and provide utility functions for user management. Built on top of Auth.js’s useSession hook, it offers enhanced functionality.

Here’s an overview of the useUser hook:

// src/@auth/useUser.tsx
import { useSession, signOut } from 'next-auth/react';
// ... furtherimports ...

function useUser(): useUser {
  const { data, update } = useSession();

  const user = useMemo(() => data?.db, [data]);
  const isGuest = useMemo(() => !user?.role || user?.role?.length === 0, [user]);

  async function handleUpdateUser(updates: Partial<User>) {
    // Modify user data
  }

  async function handleUpdateUserSettings(newSettings: User['settings']) {
    // Adjust user settings
  }

  // ... other utility functions ...

  return {
    data: user,
    isGuest,
    signOut: handleSignOut,
    updateUser: handleUpdateUser,
    updateUserSettings: handleUpdateUserSettings
  } as useUser;
}

export default useUser;

The useUser hook offers the following features:

  • Access to the current user’s data
  • An indicator for whether the user is a guest
  • Functions to modify user data and settings
  • A wrapper for the sign-out functionality

You can utilize this hook in your components to easily manage and access user data:

import useUser from '@auth/useUser';

function UserProfile() {
  const { data: user, updateUser, isGuest } = useUser();

  if (isGuest) {
    return <p>Please sign in to view your profile.</p>;
  }

  return (
    <div>
      <h1>Welcome, {user.displayName}</h1>
      {/* Add more user profile information and management here */}
    </div>
  );
}

By utilizing the custom session handling and the useUser hook, Singularity React delivers a robust and adaptable approach to managing user authentication and data across your application.

Further Resources

For additional details and advanced usage, consult the following resources:

  • Auth.js Official Documentation

By integrating Auth.js with Next.js App Router, Singularity React offers a secure, customizable, and efficient authentication system that works seamlessly with server components and can be tailored to meet your project’s unique needs.