Socket
Book a DemoInstallSign in
Socket

@imtbl/auth-nextjs

Package Overview
Dependencies
Maintainers
4
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@imtbl/auth-nextjs

Next.js authentication integration for Immutable SDK using NextAuth

latest
Source
npmnpm
Version
0.0.1-alpha.0
Version published
Maintainers
4
Created
Source

@imtbl/auth-nextjs

Next.js authentication integration for Immutable SDK using NextAuth.js.

This package bridges @imtbl/auth popup-based authentication with NextAuth.js session management, providing:

  • Server-side session storage in encrypted JWT cookies
  • Automatic token refresh on both server and client
  • Full SSR support with getServerSession
  • React hooks for easy client-side authentication

Installation

pnpm add @imtbl/auth-nextjs next-auth

Quick Start

1. Set Up Auth API Route

// pages/api/auth/[...nextauth].ts
import { ImmutableAuth } from "@imtbl/auth-nextjs";

export default ImmutableAuth({
  clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
  redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
});

2. Create Callback Page

// pages/callback.tsx
import { CallbackPage } from "@imtbl/auth-nextjs/client";

const config = {
  clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
  redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
};

export default function Callback() {
  return <CallbackPage config={config} />;
}

3. Add Provider to App

// pages/_app.tsx
import { ImmutableAuthProvider } from "@imtbl/auth-nextjs/client";

const config = {
  clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
  redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
};

export default function App({ Component, pageProps }: AppProps) {
  return (
    <ImmutableAuthProvider config={config} session={pageProps.session}>
      <Component {...pageProps} />
    </ImmutableAuthProvider>
  );
}

4. Use in Components

import { useImmutableAuth } from "@imtbl/auth-nextjs/client";

function LoginButton() {
  const { user, isLoading, signIn, signOut } = useImmutableAuth();

  if (isLoading) return <div>Loading...</div>;

  if (user) {
    return (
      <div>
        <span>Welcome, {user.email}</span>
        <button onClick={signOut}>Logout</button>
      </div>
    );
  }

  return <button onClick={signIn}>Login with Immutable</button>;
}

5. Access Session Server-Side (SSR)

// pages/profile.tsx
import { getImmutableSession } from "@imtbl/auth-nextjs/server";
import type { GetServerSideProps } from "next";

const config = {
  clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
  redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
};

export default function ProfilePage({ user }) {
  if (!user) return <p>Not logged in</p>;
  return <h1>Welcome, {user.email}</h1>;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const session = await getImmutableSession(ctx.req, ctx.res, config);
  return { props: { user: session?.user ?? null } };
};

6. Protect Pages (Optional)

// pages/dashboard.tsx
import { withPageAuthRequired } from "@imtbl/auth-nextjs/server";

const config = {
  clientId: process.env.NEXT_PUBLIC_IMMUTABLE_CLIENT_ID!,
  redirectUri: `${process.env.NEXT_PUBLIC_BASE_URL}/callback`,
};

function DashboardPage() {
  return <h1>Dashboard (protected)</h1>;
}

export default DashboardPage;

// Redirects to /login if not authenticated
export const getServerSideProps = withPageAuthRequired(config);

Configuration Options

The ImmutableAuthConfig object accepts the following properties:

PropertyTypeRequiredDefaultDescription
clientIdstringYes-Immutable OAuth client ID
redirectUristringYes-OAuth callback redirect URI
logoutRedirectUristringNo-Where to redirect after logout
audiencestringNo"platform_api"OAuth audience
scopestringNo"openid profile email offline_access transact"OAuth scopes
authenticationDomainstringNo"https://auth.immutable.com"Authentication domain

Environment Variables

# .env.local
NEXT_PUBLIC_IMMUTABLE_CLIENT_ID=your-client-id
NEXT_PUBLIC_BASE_URL=http://localhost:3000

# Required by NextAuth for cookie encryption
NEXTAUTH_SECRET=generate-with-openssl-rand-base64-32
NEXTAUTH_URL=http://localhost:3000

Generate a secret:

openssl rand -base64 32

API Reference

Main Exports (@imtbl/auth-nextjs)

ExportDescription
ImmutableAuth(config, overrides?)Creates NextAuth handler (use in API route)
refreshAccessToken(token)Utility to refresh an expired access token
isTokenExpired(token)Utility to check if a token is expired

Types:

TypeDescription
ImmutableAuthConfigConfiguration options
ImmutableAuthOverridesNextAuth options override type
ImmutableUserUser profile type
ImmutableTokenDataToken data passed to credentials provider
ZkEvmInfozkEVM wallet information type
WithPageAuthRequiredOptionsOptions for page protection

Client Exports (@imtbl/auth-nextjs/client)

ExportDescription
ImmutableAuthProviderReact context provider (wraps NextAuth SessionProvider)
useImmutableAuth()Hook for authentication state and methods (see below)
useAccessToken()Hook returning getAccessToken function
CallbackPagePre-built callback page component for OAuth redirects

useImmutableAuth() Return Value:

PropertyTypeDescription
userImmutableUser | nullCurrent user profile (null if not authenticated)
sessionSession | nullFull NextAuth session with tokens
isLoadingbooleanWhether authentication state is loading
isAuthenticatedbooleanWhether user is authenticated
signIn() => Promise<void>Sign in with Immutable (opens popup)
signOut() => Promise<void>Sign out from both NextAuth and Immutable
getAccessToken() => Promise<string>Get a valid access token (refreshes if needed)
authAuth | nullThe underlying Auth instance (for advanced use)

Types:

TypeDescription
ImmutableAuthProviderPropsProps for the provider component
UseImmutableAuthReturnReturn type of useImmutableAuth
CallbackPagePropsProps for CallbackPage component
ImmutableAuthConfigRe-exported configuration type
ImmutableUserRe-exported user type

Server Exports (@imtbl/auth-nextjs/server)

ExportDescription
getImmutableSession(req, res, config)Get session server-side
withPageAuthRequired(config, options?)HOC for protecting pages with auth check

withPageAuthRequired Options:

OptionTypeDefaultDescription
loginUrlstring"/login"URL to redirect to when not authenticated
returnTostring | falsecurrent pageURL to redirect to after login (false to disable)
getServerSideProps(ctx, session) => ...-Custom getServerSideProps that runs after auth check

Example with custom getServerSideProps:

export const getServerSideProps = withPageAuthRequired(config, {
  loginUrl: "/auth/signin",
  async getServerSideProps(ctx, session) {
    // session is guaranteed to exist here
    const data = await fetchData(session.accessToken);
    return { props: { data } };
  },
});

Types:

TypeDescription
WithPageAuthRequiredOptionsBasic options for page protection
WithPageAuthRequiredFullOptionsFull options including getServerSideProps
WithPageAuthRequiredPropsProps added to protected pages (session)

How It Works

  • Login: User clicks login → @imtbl/auth opens popup → tokens returned
  • Session Creation: Tokens passed to NextAuth's credentials provider → stored in encrypted JWT cookie
  • Token Refresh: NextAuth JWT callback automatically refreshes expired tokens using refresh_token
  • SSR: getServerSession() reads and decrypts cookie, providing full session with tokens
  • Auto-hydration: If localStorage is cleared but session cookie exists, the Auth instance is automatically hydrated from session tokens

License

Apache-2.0

FAQs

Package last updated on 19 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts