Skip to content

Sign In API (api/auth/signin.ts)

Endpoint Overview

Handles user authentication through email and password credentials. Validates user input, manages authentication state, and returns session tokens.

Request Handlers

POST

  • Body:
    {
      email: string;     // User's email address
      password: string;  // User's password
      redirect?: string; // Optional redirect URL
    }
    
  • Response:
    {
      ok: boolean;           // Authentication success
      error?: string;        // Error message if failed
      url?: string;          // Redirect URL if successful
      status: number;        // HTTP status code
    }
    
  • Status: 200 OK, 401 Unauthorized, 400 Bad Request

Error Handling

try {
  const result = await signIn('credentials', {
    email,
    password,
    redirect: false
  });

  if (!result?.ok) {
    throw new Error('Invalid credentials');
  }
} catch (error) {
  return {
    ok: false,
    error: error.message,
    status: 401
  };
}

Common errors: - 401: Invalid credentials - 400: Missing required fields - 400: Invalid email format - 429: Too many attempts - 500: Authentication error

Usage Example

const response = await fetch("/api/auth/signin", {
  method: "POST",
  headers: { 
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    email: "user@example.com",
    password: "securePassword123"
  })
});

const result = await response.json();
if (result.ok) {
  window.location.href = result.url;
}

Implementation Details

  • Uses NextAuth.js
  • Implements credentials provider
  • Validates email format
  • Verifies password hash
  • Manages session tokens
  • Handles redirects
  • Supports rate limiting
  • Tracks login attempts
  • Uses secure cookies

Pages/Components Referenced By

Notes

  • Requires valid credentials
  • Rate limited for security
  • Supports custom redirects
  • Uses JWT tokens
  • Maintains session state
  • Validates input data
  • Handles auth errors
  • Secure password check
  • Tracks auth attempts