Thanks to visit codestin.com
Credit goes to docs.nhost.io

Skip to content

Session

Session management module for Nhost authentication

This module exports utilities for managing authentication sessions across different environments and storage backends. It provides:

  • Session storage abstractions for different environments
  • Session persistence and synchronization
  • Automatic token refresh mechanisms

This is an advanced submodule of the Nhost SDK, primarily used internally but it is exposed for advanced use cases.

Cookie-based storage implementation. This storage uses web browser cookies to store the session so it’s not available in server-side environments. It is useful though for synchronizing sessions between client and server environments.

new CookieStorage(options?: object): CookieStorage;

Creates a new CookieStorage instance

ParameterTypeDescription
options?{ cookieName?: string; expirationDays?: number; sameSite?: "strict" | "lax" | "none"; secure?: boolean; }Configuration options
options.cookieName?stringName of the cookie to use (defaults to “nhostSession”)
options.expirationDays?numberNumber of days until the cookie expires (defaults to 30)
options.sameSite?"strict" | "lax" | "none"SameSite policy for the cookie (defaults to “lax”)
options.secure?booleanWhether to set the Secure flag on the cookie (defaults to true)

CookieStorage

get(): Session | null;

Gets the session from cookies

Session | null

The stored session or null if not found

SessionStorageBackend.get

remove(): void;

Removes the session cookie

void

SessionStorageBackend.remove

set(value: Session): void;

Sets the session in a cookie

ParameterTypeDescription
valueSessionThe session to store

void

SessionStorageBackend.set


Browser localStorage implementation of StorageInterface. Persists the session across page reloads and browser restarts.

new LocalStorage(options?: object): LocalStorage;

Creates a new LocalStorage instance

ParameterTypeDescription
options?{ storageKey?: string; }Configuration options
options.storageKey?stringThe key to use in localStorage (defaults to “nhostSession”)

LocalStorage

get(): Session | null;

Gets the session from localStorage

Session | null

The stored session or null if not found

SessionStorageBackend.get

remove(): void;

Removes the session from localStorage

void

SessionStorageBackend.remove

set(value: Session): void;

Sets the session in localStorage

ParameterTypeDescription
valueSessionThe session to store

void

SessionStorageBackend.set


In-memory storage implementation for non-browser environments or when persistent storage is not available or desirable.

new MemoryStorage(): MemoryStorage;

MemoryStorage

get(): Session | null;

Gets the session from memory

Session | null

The stored session or null if not set

SessionStorageBackend.get

remove(): void;

Clears the session from memory

void

SessionStorageBackend.remove

set(value: Session): void;

Sets the session in memory

ParameterTypeDescription
valueSessionThe session to store

void

SessionStorageBackend.set


A wrapper around any SessionStorageInterface implementation that adds the ability to subscribe to session changes.

new SessionStorage(storage: SessionStorageBackend): SessionStorage;

Creates a new SessionStorage instance

ParameterTypeDescription
storageSessionStorageBackendThe underlying storage implementation to use

SessionStorage

get(): Session | null;

Gets the session from the underlying storage

Session | null

The stored session or null if not found

onChange(callback: SessionChangeCallback): () => void;

Subscribe to session changes

ParameterTypeDescription
callbackSessionChangeCallbackFunction that will be called when the session changes

An unsubscribe function to remove this subscription

(): void;

void

remove(): void;

Removes the session from the underlying storage and notifies subscribers

void

set(value: Session): void;

Sets the session in the underlying storage and notifies subscribers

ParameterTypeDescription
valueSessionThe session to store

void

Decoded JWT token payload with processed timestamps and Hasura claims

[key: string]: unknown

Any other JWT claims

optional exp: number;

Token expiration time as Date object

optional https://hasura.io/jwt/claims: Record<string, unknown>;

Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays

optional iat: number;

Token issued at time as Date object

optional iss: string;

Token issuer

optional sub: string;

Token subject (user ID)


User authentication session containing tokens and user information

accessToken: string

JWT token for authenticating API requests Example - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Session.accessToken

accessTokenExpiresIn: number

Expiration time of the access token in seconds Example - 900 Format - int64

Session.accessTokenExpiresIn

decodedToken: DecodedToken

Decoded JWT token payload with processed timestamps and Hasura claims

refreshToken: string

Token used to refresh the access token Example - "2c35b6f3-c4b9-48e3-978a-d4d0f1d42e24" Pattern - \b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b

Session.refreshToken

refreshTokenId: string

Identifier for the refresh token Example - "2c35b6f3-c4b9-48e3-978a-d4d0f1d42e24" Pattern - \b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b

Session.refreshTokenId

optional user: User;

User profile and account information

Session.user


Session storage interface for session persistence. This interface can be implemented to provide custom storage solutions.

get(): Session | null;

Get the current session from storage

Session | null

The stored session or null if not found

remove(): void;

Remove the session from storage

void

set(value: Session): void;

Set the session in storage

ParameterTypeDescription
valueSessionThe session to store

void

type SessionChangeCallback = (session: Session | null) => void

Callback function type for session change subscriptions

ParameterType
sessionSession | null

void

const DEFAULT_SESSION_KEY: 'nhostSession' = 'nhostSession'

Default storage key used for storing the Nhost session

function detectStorage(): SessionStorageBackend

Detects the best available storage implementation for the current environment.

The detection process follows this order:

  1. Try to use localStorage if we’re in a browser environment
  2. Fall back to in-memory storage if localStorage isn’t available

SessionStorageBackend

The best available storage implementation as a SessionStorageBackend


function refreshSession(
auth: Client,
storage: SessionStorage,
marginSeconds: number
): Promise<Session | null>

Refreshes the authentication session if needed

This function checks if the current session needs to be refreshed based on the access token expiration time. If a refresh is needed, it will attempt to refresh the token using the provided auth client.

ParameterTypeDefault valueDescription
authClientundefinedThe authentication client to use for token refresh
storageSessionStorageundefinedThe session storage implementation
marginSecondsnumber60The number of seconds before the token expiration to refresh the session. If the token is still valid for this duration, it will not be refreshed. Set to 0 to force the refresh.

Promise<Session | null>

A promise that resolves to the current session (refreshed if needed) or null if no session exists