Skip to main content
Retrieve session credentials to authenticate requests to your backend. When a user logs in to your app and becomes authenticated, MoonKey issues the user session credentials. These credentials allow your backend to verify that the requesting user is truly authenticated.

Session Credentials

MoonKey provides two types of session credentials:

Session Token

An opaque token that can be verified through the MoonKey API:
  • Must be verified via /sessions/verify API endpoint
  • Can be instantly revoked
  • No user information exposed in the token itself

Session JWT

A JSON Web Token (JWT) signed with RS256 that can be verified independently:
  • Can be verified using public keys without API call
  • Contains session information in claims
  • Expires after 5 minutes but can be refreshed
Learn more about the differences in the Session Token vs JWT guide.

Getting Session Credentials

To retrieve the current user’s session credentials, use the getSessionTokens method from the useMoonKey hook:

Import

Basic Usage

Return Value

The getSessionTokens method returns:
  • An object with sessionToken and sessionJwt if the user is authenticated
  • null if the user is not authenticated

Sending Session Credentials

When making requests to your backend, include the session credentials in the request headers.

With fetch

Using the session token (recommended for most use cases):
Using the session JWT (for offline verification):

With axios

With custom hooks

Create a reusable hook for authenticated requests:

Common Patterns

API Client Wrapper

Create an API client that automatically includes session credentials:

With React Query

Integrate with React Query for data fetching:

Error Handling

Properly handle authentication errors:

With Next.js API Routes

Make authenticated requests to Next.js API routes:

Best Practices

Always Check for Null

The getSessionTokens method returns null when the user is not authenticated:

Handle Expired Sessions

Session tokens can expire or become invalid:

Choose the Right Credential Type

Use Session Token when:
  • You need real-time revocation
  • Security is the top priority
  • You’re making requests to your own backend
Use Session JWT when:
  • You need offline verification
  • Performance is critical (no API call needed)
  • You’re integrating with external JWT-based systems

Secure Storage

The MoonKey SDK automatically handles secure storage of session credentials in IndexedDB. You don’t need to manually store these values.