After successful authentication, Hanko generates a session token that is stored as a cookie. Use the session token to authenticate requests to your backend. This guide demonstrates how to implement session token validation in JavaScript to ensure that only properly authenticated users can access your application’s protected resources.

Get the Hanko API URL

Retrieve the API URL from the Hanko console.

If you are self-hosting Hanko you need to provide your own URL.

Steps to Authenticate Requests

  1. Retrieve the session token.

  2. Verify the Session token using the Hanko Validate API endpoint.

Example function

The following section demonstrates how to validate session tokens against the Hanko backend. The specific implementation for retrieving the session token cookie will vary depending on your JavaScript runtime environment and framework.

index.ts
// Types and interfaces
interface TokenValidator {
  validateToken(token: string): Promise<boolean>;
}

interface ValidationResponse {
  is_valid: boolean;
}

// Token validator implementation
class HankoTokenValidator implements TokenValidator {
  constructor(private readonly hankoApiUrl: string) {}

  async validateToken(token: string): Promise<boolean> {
    if (!token || token.length === 0) {
      return false;
    }

    try {
      const response = await fetch(`${this.hankoApiUrl}/sessions/validate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ session_token: token }),
      });

      if (!response.ok) {
        return false;
      }

      const validationData = await response.json() as ValidationResponse;
      return validationData.is_valid;
    } catch (error) {
      console.error('Token validation error:', error);
      return false;
    }
  }
}

Try it yourself

Hono.js example (React frontend)

Full source code available at GitHub.

Node and Express.js example (React frontend)

Full source code available at GitHub.

Node and Express.js example (Vue frontend)

Full source code available at GitHub.

Node and Express.js example (Svelte frontend)

Full source code available at GitHub.