@smg-automotive/auth
v9.0.1
Published
SMG Automotive auth package
Readme
auth-pkg
Usage
npm install @smg-automotive/authConfiguration
You need following environment variables to be set:
To communicate with automotive APIs:
API_ROOTAPI_VERSION
Those variables are most likely already set in your project if you're using any of the automotive APIs.
CONFIG_ENV- The current stageThis is can be
development,branch,preprodorproductionand 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_IDAUTH0_DOMAINAUTH0_SESSION_NAMEAUTH0_AUDIENCEAUTH0_SECRETAUTH0_CLIENT_SECRETAUTH0_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 totrueto 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 datauseAuthConfig- a hook to access the auth configgetAccessToken- a helper to get the access token. It can be used in the client-side data fetching logicswitchSelectedTenant- a helper to switch the selected tenant (cookie-only; sets the selected tenant cookie and reloads the page, no re-login). Accepts an optionalonFailure(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, orUNKNOWN_ERRORif the response has no code.
Server-side (exposed from @smg-automotive/auth/server)
isLoggedIn- a helper to check if the user is logged ingetUser- a helper to get the user datagetAccessToken- 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:profileEnable 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 devWhat 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-pkgRelease 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 /.
