Skip to main content

Overview

The timezone middleware detects user timezone from headers, cookies, or client hints for proper time display. Use it when you need:
  • Time localization
  • Timezone-aware scheduling
  • User time preferences

Installation

Quick Start

Configuration

Options

Examples

Basic Detection

Custom Header

With Default

Client-Side Detection

API Reference

Functions

Common Timezones

Technical Details

Implementation

The timezone middleware uses a multi-source detection strategy to identify the user’s timezone:
  1. Context Storage: Timezone information is stored in the request context using a type-safe context key
  2. Info Structure: Contains three key pieces of information:
    • Name: IANA timezone identifier (e.g., “America/New_York”)
    • Location: Parsed time.Location object for time conversions
    • Offset: UTC offset in seconds for the current time
  3. Lookup Order: Configurable detection precedence via the Lookup option (default: “header,cookie,query”)
  4. Validation: Invalid timezone names automatically fall back to the configured default
  5. Cookie Management: Optional automatic cookie setting with configurable max age (default: 30 days)

Detection Flow

Helper Functions

The middleware provides several convenience functions:
  • Get(c): Returns complete timezone info
  • Location(c): Returns time.Location for time operations
  • Name(c): Returns timezone name string
  • Offset(c): Returns UTC offset in seconds
  • Now(c): Returns current time in detected timezone

Convenience Constructors

  • FromHeader(header): Only check specific header
  • FromCookie(name): Only check specific cookie
  • WithDefault(tz): Set custom default timezone

Best Practices

  • Default to UTC for storage
  • Convert to user timezone for display
  • Use IANA timezone names
  • Detect via JavaScript for accuracy

Testing

The middleware includes comprehensive test coverage for all functionality: