Skip to main content

Version: v1

Authentication Flow

This document describes the authentication mechanism for accessing protected API endpoints, including token management and refresh logic.


Overview

The authentication system uses:

  • Short-lived access tokens (15 minutes)
  • Long-lived refresh tokens (stored in HTTP-only cookies)
  • Axios interceptors for automatic token refresh
  • Singleton pattern to prevent duplicate refresh requests

Authentication Flow

1. Registration

  • Endpoint: POST /auth/register
  • Input: email, password
  • Description: Sends an OTP to the user's email for verification.

2. Email Verification

  • Endpoint: POST /auth/email/verify
  • Input: email, otp, password
  • Description: Verifies the user's email and activates the account.

3. Login

  • Endpoint: POST /auth/login
  • Input: email, password, storeId
  • Response:
    • accessToken (to be stored client-side)
    • refreshToken set as an HTTP-only cookie
  • Description: Customer information and verification status

4. Refresh Access Token

  • Endpoint: GET /auth/refresh/:storeId

  • Description: After a successful login, the server sets a secure, HTTP-only refresh token cookie and returns a short-lived accessToken (valid for 15 minutes). This endpoint allows you to obtain a new access token without requiring the user to log in again.

  • How It Works: This endpoint reads the refresh token from the cookie and returns a new access token if the session is still valid. You should automatically call this using an Axios interceptor when receiving a 401 Unauthorized response due to token expiry.

  • Learn More: For detailed implementation (including code for Axios interceptors and retry logic), see the full Token Management Guide.

warning

This refresh endpoint must be called after login because it relies on a server-set HTTP-only cookie (refresh-token) that is only issued during the login process.

5. Logout

  • Endpoint: POST /auth/logout
  • Description: Logs out the user by invalidating the current session. This removes the associated refresh token (stored in a server-set HTTP-only cookie), effectively ending the session.

Flow Diagram

Flow Diagram


Error Handling

ScenarioAction
Invalid/expired access tokenAutomatic refresh attempt
Failed refresh (invalid refresh token)Redirect to login
403 ForbiddenCheck user permissions
Network errorsRetry logic or display error

Security Considerations

  1. Refresh Token Protection:

    • Stored in HTTP-only, Secure, SameSite cookies
    • Not accessible via JavaScript
  2. Access Token:

    • Short-lived (15 minutes)
    • Stored in memory or localStorage
    • Sent via Authorization header

Best Practices

  1. Always use HTTPS in production
  2. Implement proper token invalidation on logout
  3. Monitor for unusual token refresh patterns
  4. Set appropriate token lifetimes based on security requirements
  5. Consider implementing session timeout warnings