npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@smg-automotive/auth

v9.0.1

Published

SMG Automotive auth package

Readme

auth-pkg

CircleCI semantic-release

Usage

npm install @smg-automotive/auth

Configuration

You need following environment variables to be set:

  • To communicate with automotive APIs:

    • API_ROOT
    • API_VERSION

    Those variables are most likely already set in your project if you're using any of the automotive APIs.

  • CONFIG_ENV - The current stage

    This is can be development, branch, preprod or production and is used to determine the correct configuration. It's most likely already set in your project.

  • PROXY_REQUEST_PATH_SEGMENT - The path segment on which your application is mounted.

  • Localization

    • DEFAULT_LOCALE - The default locale of the application.
    • SUPPORTED_LOCALES - All supported locales of the application, comma separated.
  • Auth0 configuration

    • AUTH0_CLIENT_ID
    • AUTH0_DOMAIN
    • AUTH0_SESSION_NAME
    • AUTH0_AUDIENCE
    • AUTH0_SECRET
    • AUTH0_CLIENT_SECRET
    • AUTH0_CUSTOM_AUTH_COOKIE_NAMES - [optional] comma separated list of auth related cookies to be cleared on logout

    Check out the Auth0 docs for more information.

  • Redis Session Store

    • AUTH0_CUSTOM_REDIS_URL: When present the package will create a redis session store instead of using cookies to store the session

Example: redis://default:devpassword123@localhost:6379

The consuming project needs to enable node js middleware in next

// middleware.ts
...
export const config = { runtime: "nodejs" };
  • Debug flag to force a token refresh on every interval
    • AUTH0_DEBUG_FORCE_TOKEN_REFRESH - [optional] set to true to force a token refresh on every interval

Auth Context

This package exposes the AuthProvider. It exposes the auth configuration and pre-caches the user data.

You want to include the AuthProvider on the top level of your application and supply the props obtained server-side from auth0. getAuthProps handles fetching those props for the Next.js app router.

Pages router support has been removed. Use the app router with getAuthProps.

App Router

Use getAuthProps in your layout (or other server components) and pass the result to the AuthProvider.

// src/app/layout.tsx
import { FC, PropsWithChildren } from 'react';

import { AuthProvider } from '@smg-automotive/auth';
import { getAuthProps } from '@smg-automotive/auth/server';

const Layout: FC<PropsWithChildren> = ({ children }) => {
  const brand = yourBrandDerivingLogic();
  const language = yourLanguageDetectionLogic();
  const protocol = yourProtocolDetectionLogic();
  const host = yourHostDetectionLogic();

  const authProps = await getAuthProps({ brand, protocol, host });

  return (
    <AuthProvider brand={brand} language={language} {...authProps}>
      {children}
    </AuthProvider>
  );
};

getAuthProps will handle the redirect to the login page if refreshing the auth token is not possible.

You can pass an errorHandler of your choice to the AuthProvider to handle errors. Since the provider is a client component you need to mark it as a server action.

const onError = async (error) => {
  'use server';
  // your error handling logic
};

Hooks and helpers

The package provides following hooks and helpers for session and user handling:

Client-side (exposed from @smg-automotive/auth)
  • useUser - a hook to access the user data
  • useAuthConfig - a hook to access the auth config
  • getAccessToken - a helper to get the access token. It can be used in the client-side data fetching logic
  • switchSelectedTenant - a helper to switch the selected tenant (cookie-only; sets the selected tenant cookie and reloads the page, no re-login). Accepts an optional onFailure(errorCode) callback; on 401 the helper redirects to login to re-authenticate, otherwise the error code from the response (e.g. MISSING_SELLER_ID, SELLER_NOT_ALLOWED) is passed to the callback, or UNKNOWN_ERROR if the response has no code.
Server-side (exposed from @smg-automotive/auth/server)
  • isLoggedIn - a helper to check if the user is logged in
  • getUser - a helper to get the user data
  • getAccessToken - a helper to get the access token for server-side data fetching
Login and logout links

This package also provides utility functions to generate login and logout links.

import { getLoginLink, getLogoutLink } from '@smg-automotive/auth';

They expect the auth0Config to be passed as an argument, you can obtain it from the config object in the auth context.

const auth0Config = useAuthConfig();
const loginLink = getLoginLink({ auth0Config });

Protecting routes with middleware

We provide a middleware to protect routes from unauthenticated access. It will redirect to the login page if the user is not authenticated.

// src/middleware.ts
import { NextFetchEvent, NextRequest } from 'next/server';

import { authMiddleware } from '@smg-automotive/auth/edge';

const isProtectedRoute = (path: string): boolean => {
  // your logic to determine whether the route is protected
};

export default function middleware(
  request: NextRequest,
  event: NextFetchEvent,
) {
  const language = yourLanguageDetectionLogic();
  const protocol = yourProtocolDetectionLogic();
  const host = yourHostDetectionLogic();
  const brand = yourBrandDetectionLogic();

  return authMiddleware({
    request,
    isProtectedRoute,
    language,
    protocol,
    host,
  });
}

Auth0 integration routes are handled by the middleware. You need to make sure that the middleware is invoked for all the route patters except the static assets, image optimisation and metadata files.

Debugging

This package includes comprehensive debug instrumentation using the debug package to help track and troubleshoot authentication issues. To enable debug logging, set the DEBUG environment variable.

Available Debug Namespaces

The package uses the namespace pattern @smg-automotive/auth:* with the following sub-namespaces:

  • @smg-automotive/auth:middleware - Main auth middleware flow
    • Request processing, route checks, Auth0 middleware calls, cross-domain logout detection
  • @smg-automotive/auth:user - User retrieval and enrichment
    • Session retrieval, user fetching, user enrichment with entitlements
  • @smg-automotive/auth:token - Token operations
    • Token refresh decisions (including expiration times), access token retrieval, token endpoint handling
  • @smg-automotive/auth:protectRoute - Route protection
    • Protected route checks, session validation, token refresh for protected routes
  • @smg-automotive/auth:logout - Logout operations
    • Cross-domain logout flow, cookie deletion, returnTo URL validation
  • @smg-automotive/auth:profile - User profile handling
    • Profile requests, user enrichment, entitlement loading errors

Usage

Enable all auth debugging:

DEBUG=@smg-automotive/auth:*

Enable specific namespaces:

# Enable middleware and token debugging
DEBUG=@smg-automotive/auth:middleware,@smg-automotive/auth:token

# Enable user and profile debugging
DEBUG=@smg-automotive/auth:user,@smg-automotive/auth:profile

Enable debugging in your Next.js application by setting the environment variable:

# .env.local
DEBUG=@smg-automotive/auth:*

Or pass it when running your application:

DEBUG=@smg-automotive/auth:* npm run dev

What Gets Logged

The debug instrumentation logs:

  • Request flow: Path, host, protocol, and method for each request
  • Session state: Whether sessions exist, user presence, session data retrieval
  • Token operations: Token expiration times, refresh decisions, token retrieval success/failure
  • User data: User IDs, seller IDs, email addresses (when available), entitlement presence
  • Route protection: Protected route checks, redirect decisions
  • Logout flow: Cross-domain logout initiation, cookie deletion operations
  • Errors: Authentication errors with error codes and messages (without exposing sensitive tokens)

All debug logs are structured and include relevant context while avoiding sensitive data like tokens or passwords.

Fixtures

This package also provides fixture factories for the:

  • auth0 configuration
  • private user
  • professional user
  • multi-tenant user
  • private seller entitlements
  • professional seller entitlements

You can leverage them in your tests.

import {
  authConfig,
  privateUser,
  professionalUser,
  multiTenantUser,
  privateSellerEntitlements,
  professionalSellerEntitlements,
} from '@smg-automotive/auth/fixtures';

Test environment setup

Environment extension

Ensure that TextEncoder, TextDecoder and fetch are available in the test environment. To make this easier we expose a @smg-automotive/auth/test/environment-setup module that you can add to jest setup:

// jest.config.js
const jestConfig = {
  setupFilesAfterEnv: ['@smg-automotive/auth/test/environment-setup'],
};

ESM modules transpilation

auth0/nextjs-auth0 and some other transient dependencies are now pure ESM modules. Unfortunately, jset still struggles with ESM support, and when using next/jest the setup is quite challenging. To that end we expose a @smg-automotive/auth/test/setup that can whitelist the required ESM modules for transpilation.

// jest.config.js
const nextJest = require('next/jest.js');
const {
  transpileESMModulesForJest,
} = require('@smg-automotive/auth/test/setup');

const createJestConfig = nextJest({ dir: './' });

const customJestConfig = {
  // your custom jest config
};

module.exports = transpileESMModulesForJest(createJestConfig(customJestConfig));

Ensure you have configuration of the test environment

All required configuration variables need to be set and loaded into the test environment.

Development

You can link your local npm package to integrate it with any local project:

cd smg-automotive-auth-pkg
npm run build

cd <project directory>
npm link ../smg-automotive-auth-pkg

Release a new version

New versions are released on the ci using semantic-release as soon as you merge into master. Please make sure your merge commit message adheres to the corresponding conventions and your branch name does not contain forward slashes /.