### Install and Configure Umami Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Clone the repository, install dependencies, configure the database connection and application secret using a .env file, then build and start the application. ```bash git clone https://github.com/umami-software/umami.git cd umami pnpm install cat > .env << EOF DATABASE_URL=postgresql://user:password@localhost:5432/umami APP_SECRET=$(openssl rand -base64 32) EOF pnpm run build pnpm run start ``` -------------------------------- ### Start Server Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Execute this command to start the Umami server after building the application. ```bash npm run start ``` -------------------------------- ### Install Umami with Docker Source: https://github.com/umami-software/umami/blob/master/README.md Pull the latest Umami Docker image or deploy using Docker Compose for a full stack setup including PostgreSQL. ```bash docker pull docker.umami.is/umami-software/umami:latest ``` ```bash docker compose up -d ``` -------------------------------- ### Build and Start Umami Application Source: https://github.com/umami-software/umami/blob/master/README.md Build the Umami application for production. This step also creates database tables and a default admin user. Then, start the application. ```bash pnpm run build ``` ```bash pnpm run start ``` -------------------------------- ### Install Umami Dependencies Source: https://github.com/umami-software/umami/blob/master/README.md Clone the Umami repository and install project dependencies using pnpm. Ensure Node.js v18.18+ and PostgreSQL v12.14+ are installed. ```bash git clone https://github.com/umami-software/umami.git cd umami pnpm install ``` -------------------------------- ### Not Found Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response indicating that a requested resource does not exist. ```json { "error": { "message": "Not found", "code": "not-found", "status": 404 } } ``` -------------------------------- ### Update Umami from Source Source: https://github.com/umami-software/umami/blob/master/README.md Update your local Umami installation by pulling the latest changes, installing new dependencies, and rebuilding the application. ```bash git pull pnpm install pnpm build ``` -------------------------------- ### Example: Convert Object to Array Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/data.md Demonstrates converting an object's values into an array. ```javascript const obj = { a: 1, b: 2, c: 3 }; objectToArray(obj); // [1, 2, 3] const data = { name: 'John', age: 30 }; objectToArray(data); // ['John', 30] ``` -------------------------------- ### Handling Not Found Resources in JavaScript Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Example of fetching a resource and returning a not found error if it doesn't exist. ```javascript const website = await getWebsite(websiteId); if (!website) { return notFound({ message: 'Website not found' }); } ``` -------------------------------- ### Example Usage of parseAuthToken Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/jwt.md Demonstrates how to use the `parseAuthToken` function to get a user ID from the token payload and retrieve user information. ```javascript const payload = await parseAuthToken(request, secret()); if (payload?.userId) { const user = await getUser(payload.userId); } ``` -------------------------------- ### Example of getRequestFilters Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/request-response.md Demonstrates how to use getRequestFilters to extract relevant parameters from a query object. ```javascript const query = { page: '1', browser: 'Chrome', os: 'Windows', browser1: 'Firefox', // Dynamic param country: 'US' }; const filters = getRequestFilters(query); // { browser: 'Chrome', os: 'Windows', browser1: 'Firefox', country: 'US' } ``` -------------------------------- ### GET /api/config Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Get application configuration details, including version and mode information. ```APIDOC ## GET /api/config ### Description Get application configuration. ### Method GET ### Endpoint /api/config ### Response #### Success Response (200) - **version** (string) - The current version of the application. - **cloudMode** (boolean) - Indicates if the application is running in cloud mode. - **demoMode** (boolean) - Indicates if the application is running in demo mode. - **loginRequired** (boolean) - Indicates if login is required to use the application. #### Response Example ```json { "version": "3.2.0", "cloudMode": true, "demoMode": false, "loginRequired": false } ``` ``` -------------------------------- ### POST /api/auth/login Example Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md This snippet demonstrates how to authenticate a user by sending username and password to the login endpoint and retrieving an authentication token. ```javascript const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'password' }) }); const { token } = await response.json(); ``` -------------------------------- ### Example: Create KeyValue for Number Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/data.md Demonstrates creating a typed key-value pair for a number. The dataType will be 2. ```javascript createKeyValue('count', 42); // { key: 'count', value: 42, dataType: 2 } ``` -------------------------------- ### Success Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md A standard success response with data payload. ```json { "data": {...} } ``` -------------------------------- ### Unauthorized Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response indicating authentication failure or missing credentials. ```json { "error": { "message": "Unauthorized", "code": "unauthorized", "status": 401 } } ``` -------------------------------- ### Get Application Configuration - GET /api/config Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieve the current application configuration settings. Authentication is optional for this endpoint. ```json { "version": "3.2.0", "cloudMode": boolean, "demoMode": boolean, "loginRequired": boolean } ``` -------------------------------- ### Date Range Filtering Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/request-response.md This example illustrates how to filter data based on a specified date range. It parses query parameters to extract start date, end date, unit, and timezone for metric retrieval. ```APIDOC ## GET /api/metrics/{websiteId} ### Description Retrieves metrics for a specific website, allowing filtering by a date range, time unit, and timezone specified in the query parameters. ### Method GET ### Endpoint /api/metrics/{websiteId} ### Parameters #### Path Parameters - **websiteId** (string) - Required - The ID of the website for which to retrieve metrics. #### Query Parameters - **startDate** (string) - Optional - The start date for the range (e.g., YYYY-MM-DD). - **endDate** (string) - Optional - The end date for the range (e.g., YYYY-MM-DD). - **unit** (string) - Optional - The time unit for aggregation (e.g., 'day', 'week', 'month'). - **timezone** (string) - Optional - The timezone for date calculations (e.g., 'UTC', 'America/New_York'). ### Response #### Success Response (200) - **metrics** (array) - An array of metric data points. #### Response Example ```json [ { "date": "2023-10-26", "visitors": 150, "pageviews": 300 }, { "date": "2023-10-27", "visitors": 175, "pageviews": 350 } ] ``` ``` -------------------------------- ### Build and Lint Umami Project Source: https://github.com/umami-software/umami/blob/master/CONTRIBUTING.md Ensure the project builds and lints cleanly before submitting a pull request. This involves installing dependencies, building the project, and running the linter. ```bash pnpm install pnpm build pnpm lint ``` -------------------------------- ### Server Error Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response for internal server errors, indicating an unexpected condition. ```json { "error": { "message": "Server error", "code": "server-error", "status": 500 } } ``` -------------------------------- ### Example: Create KeyValue for Boolean Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/data.md Demonstrates creating a typed key-value pair for a boolean. The value becomes a string and dataType will be 3. ```javascript createKeyValue('active', true); // { key: 'active', value: 'true', dataType: 3 } ``` -------------------------------- ### Forbidden Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response for authenticated users lacking sufficient permissions for a requested resource. ```json { "error": { "message": "Forbidden", "code": "forbidden", "status": 403 } } ``` -------------------------------- ### GET /api/auth/verify Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Verifies the validity of a provided authentication token. ```APIDOC ## GET /api/auth/verify ### Description Verify the validity of a token. ### Method GET ### Endpoint /api/auth/verify ### Authentication Required (bearer token) ### Response #### Success Response (200) - **valid** (boolean) #### Error Response - **401**: Invalid or expired token ### Source `src/app/api/auth/verify/route.ts` ``` -------------------------------- ### Get Current Application Version Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/constants.md Retrieves the current application version string, typically from environment variables. ```typescript export const CURRENT_VERSION = process.env.currentVersion ``` -------------------------------- ### Example of setWebsiteDate Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/request-response.md Shows how setWebsiteDate might be used to limit the date range of query parameters for free users in cloud mode. ```javascript const parameters = { startDate, endDate }; const limited = await setWebsiteDate(websiteId, parameters); // May have earlier startDate adjusted for free users ``` -------------------------------- ### Example: Create KeyValue for Array Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/data.md Demonstrates creating a typed key-value pair for an array. The value is JSON stringified and dataType will be 5. ```javascript createKeyValue('tags', ['a', 'b']); // { key: 'tags', value: '["a","b"]', dataType: 5 } ``` -------------------------------- ### Handling Forbidden Permissions in JavaScript Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Example of checking user permissions and returning a forbidden error if insufficient. ```javascript const canDelete = await hasPermission(auth.user.role, 'website:delete'); if (!canDelete) { return forbidden(); } ``` -------------------------------- ### Get Website Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves details for a specific website using its ID. Requires authentication and access. ```APIDOC ## GET /api/websites/:websiteId ### Description Get a specific website. ### Method GET ### Endpoint /api/websites/:websiteId ### Response #### Success Response (200) - **id** (string) - Website ID - **name** (string) - Website name - **domain** (string) - Website domain - **teamId** (string) - Team ID - **createdAt** (string) - Creation timestamp - **shareId** (string) - Shareable ID - **replayConfig** (object) - Session replay configuration ### Response Example { "example": "{ \"id\": \"1\", \"name\": \"My Website\", \"domain\": \"example.com\", \"teamId\": \"1\", \"createdAt\": \"2023-01-01T12:00:00.000Z\", \"shareId\": \"abc123xyz\", \"replayConfig\": { \"replayEnabled\": true } }" } ``` -------------------------------- ### Check Node.js Version Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Ensure you have the correct Node.js version installed for Umami. This command checks the currently active Node.js version. ```bash node --version ``` -------------------------------- ### Environment Variables for Proxied Setup Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Set these environment variables when running Umami behind a reverse proxy to correctly define the base path for the application and API. ```bash BASE_PATH=/umami API_URL=/umami/api ``` -------------------------------- ### Get Specific Website Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Fetches details for a single website using its ID. Requires authentication and access permissions. ```http GET /api/websites/:websiteId ``` -------------------------------- ### Bad Request Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response for invalid request parameters or validation failures, including field-specific errors. ```json { "error": { "message": "Bad request", "code": "bad-request", "status": 400, "fieldErrors": { "email": ["Invalid email format"] } } } ``` -------------------------------- ### Authentication Header Example Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Most Umami API endpoints require authentication using a bearer token. This is typically provided in the 'Authorization' header. ```http Authorization: Bearer ``` -------------------------------- ### Create Secure User Authentication Token Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/jwt.md Creates a secure token for user authentication. This example shows how to include user ID, role, and an optional password hash fingerprint in the token payload. ```javascript const token = createSecureToken( { userId: '123', role: 'admin', pwd: hash(password) }, secret() ); ``` -------------------------------- ### Get Board Details Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves the details of a specific board, including its layout and components. Authentication is required (or share token). ```APIDOC ## GET /api/boards/:boardId ### Description Get board details. ### Method GET ### Endpoint /api/boards/:boardId ### Parameters #### Path Parameters - **boardId** (string) - Required - The ID of the board to retrieve. ### Response #### Success Response (200) - Board with layout and components ``` -------------------------------- ### Invalid Date Format Example Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Demonstrates valid ISO 8601 date string formats accepted by Umami. Incorrect formats will result in data validation errors. ```text 2024-01-15T10:30:00Z 2024-01-15T10:30:00.123Z 2024-01-15T10:30:00+05:30 ``` -------------------------------- ### secret(): string Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/crypto.md Gets the application secret key. Returns the hashed application secret from environment variables. Uses `APP_SECRET` if set, otherwise uses `DATABASE_URL` as fallback. The result is a SHA-512 hash of the secret value. ```APIDOC ## secret(): string ### Description Get the application secret key. Returns the hashed application secret from environment variables. Uses `APP_SECRET` if set, otherwise uses `DATABASE_URL` as fallback. The result is a SHA-512 hash of the secret value. ### Environment Variables - `APP_SECRET`: Primary application secret (recommended) - `DATABASE_URL`: Fallback if APP_SECRET not set ### Returns Application secret string ### Example ```javascript const appSecret = secret(); const token = createSecureToken(payload, appSecret); ``` ``` -------------------------------- ### API Endpoint with Validation Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/request-response.md This example demonstrates how to create an API endpoint that validates incoming request data against a Zod schema. It parses the request, checks for validation errors, and handles authentication before processing the data. ```APIDOC ## POST /api/users ### Description Creates a new user after validating the provided name, email, and optional age against a predefined schema. Requires user authentication. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **name** (string) - Required - User's name (1-100 characters). - **email** (string) - Required - User's email address (must be a valid email format). - **age** (number) - Optional - User's age (integer between 0 and 150). ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com", "age": 30 } ``` ### Response #### Success Response (200) - **user** (object) - Details of the created user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "John Doe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Build Application Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Run this command to build the Umami application, which includes creating database tables and the initial admin user. ```bash npm run build ``` -------------------------------- ### Configure Umami Environment Variables Source: https://github.com/umami-software/umami/blob/master/README.md Set up the DATABASE_URL in an .env file for database connection. Optionally, configure API_URL for internal API calls. ```bash DATABASE_URL=connection-url ``` ```bash postgresql://username:mypassword@localhost:5432/mydb ``` -------------------------------- ### Handle Token Validation Failure (401) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md This example shows a request that will fail due to an invalid or missing Bearer token, resulting in a 401 Unauthorized response. Ensure the Authorization header is correctly formatted as 'Bearer '. ```http GET /api/me Authorization: Bearer invalid.token.here ``` ```json { "error": { "message": "Unauthorized", "code": "unauthorized", "status": 401 } } ``` -------------------------------- ### getSalt(saltRotation, createdAt) Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/crypto.md Derives a salt from the start of a time period (day, week, or month). This is used for time-based security operations like password reset tokens or temporary sessions. ```APIDOC ## getSalt(saltRotation, createdAt) ### Description Derives a salt from the start of a time period (day, week, or month). Used for time-based security operations like password reset tokens or temporary sessions. ### Signature ```typescript function getSalt(saltRotation: string, createdAt: Date): string ``` ### Parameters #### Path Parameters - **saltRotation** (string) - Required - Rotation period ('day', 'week', or 'month'). - **createdAt** (Date) - Required - Date to base salt on. ### Returns - **string** - SHA-512 hash of the period start date ### Period Behavior - 'day': Uses start of day (00:00:00) - 'week': Uses start of week (Monday 00:00:00) - 'month': Uses start of month (1st day 00:00:00) ### Example ```javascript const daySalt = getSalt('day', new Date()); // Changes every day at midnight const monthSalt = getSalt('month', createdAt); // Changes on first of each month ``` ``` -------------------------------- ### Set Environment Variables Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Create a .env file to configure database connection and application secrets. ```bash # Create .env file cat > .env << EOF DATABASE_URL=postgresql://user:password@localhost:5432/umami APP_SECRET=$(openssl rand -base64 32) EOF ``` -------------------------------- ### Create Database Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Use this command to create a new PostgreSQL database for Umami. ```bash createdb umami ``` -------------------------------- ### Configure .env with Required and Optional Variables Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Set required and optional environment variables in the .env file for Umami. Ensure DATABASE_URL and APP_SECRET are provided. ```bash # Required DATABASE_URL=postgresql://user:pass@localhost:5432/umami APP_SECRET=your-random-secret-key # Optional PORT=3000 CLOUD_MODE=false REDIS_URL=redis://localhost:6379 ``` -------------------------------- ### Get Current User Profile Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves the profile information for the currently authenticated user. ```APIDOC ## GET /api/me ### Description Get the current authenticated user's profile. ### Method GET ### Endpoint /api/me ### Authentication Required ### Response #### Success Response (200) - **user** (object) - User details including id, username, role, and isAdmin. - **token** (string) - Authentication token. - **authKey** (string) - Authentication key. #### Response Example ```json { "user": { "id": "uuid", "username": "string", "role": "admin|user|view-only", "isAdmin": boolean }, "token": "string", "authKey": "string" } ``` ``` -------------------------------- ### Create Website Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Creates a new website entry. Requires website name and domain. Optionally assign to a team. ```http POST /api/websites Content-Type: application/json { "name": "My Website", "domain": "example.com", "teamId": "your-team-id" } ``` -------------------------------- ### Create Board Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Creates a new board with the provided name and layout parameters. Authentication is required. ```APIDOC ## POST /api/boards ### Description Create a new board. ### Method POST ### Endpoint /api/boards ### Parameters #### Request Body - **name** (string) - Required - Board name - **parameters** (object) - Required - Board layout parameters ### Response #### Success Response (200) - Created board object ``` -------------------------------- ### Create Website Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Creates a new website entry in the system. Requires authentication. ```APIDOC ## POST /api/websites ### Description Create a new website. ### Method POST ### Endpoint /api/websites ### Request Body - **name** (string) - Required - Website name - **domain** (string) - Required - Website domain - **teamId** (string) - Optional - Team ID to assign website ### Response #### Success Response (201) - **id** (string) - Website ID - **name** (string) - Website name - **domain** (string) - Website domain - **teamId** (string) - Team ID - **createdAt** (string) - Creation timestamp - **shareId** (string) - Shareable ID ### Response Example { "example": "{ \"id\": \"1\", \"name\": \"New Website\", \"domain\": \"newdomain.com\", \"teamId\": \"1\", \"createdAt\": \"2023-01-01T12:00:00.000Z\", \"shareId\": \"abc123xyz\" }" } ``` -------------------------------- ### Get Specific User by ID Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves the details of a specific user identified by their unique ID. ```APIDOC ## GET /api/users/:userId ### Description Get a specific user by ID. ### Method GET ### Endpoint /api/users/:userId ### Authentication Required ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (string) - User's unique identifier. - **username** (string) - User's username. - **role** (string) - User's role. - **createdAt** (string) - Timestamp when the user was created. #### Response Example ```json { "id": "uuid", "username": "string", "role": "admin|user|view-only", "createdAt": "timestamp" } ``` ``` -------------------------------- ### Get team details Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves detailed information about a specific team, including its members. Authentication is required. ```APIDOC ## GET /api/teams/:teamId ### Description Get team details. ### Method GET ### Endpoint /api/teams/:teamId ### Authentication Required (team member) ### Response #### Success Response (200) Team object with members ``` -------------------------------- ### Database Connection URL Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Set the PostgreSQL connection string for Umami. This is a required environment variable. ```bash DATABASE_URL=postgresql://umami:password@localhost:5432/umami ``` -------------------------------- ### Server and API Configuration Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Set the server port, API URL, and base path for the application. Useful when running behind a reverse proxy. ```bash PORT=3000 API_URL=/internal-api BASE_PATH=/umami ``` -------------------------------- ### Configure Umami and PostgreSQL with Docker Compose Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Define Umami and its PostgreSQL database service in a docker-compose.yml file. This includes image versions, environment variables, ports, and volumes. ```yaml version: '3' services: umami: image: umami-software/umami:latest environment: DATABASE_URL: postgresql://umami:password@postgres:5432/umami APP_SECRET: your-secret ports: - "3000:3000" depends_on: - postgres postgres: image: postgres:14 environment: POSTGRES_DB: umami POSTGRES_USER: umami POSTGRES_PASSWORD: password volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: ``` -------------------------------- ### List Websites API Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Retrieve a list of all configured websites. Requires a Bearer token in the Authorization header. ```bash GET /api/websites Authorization: Bearer ``` -------------------------------- ### Get Shared Resource by ID Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves a shared resource using its unique ID. Authentication is not required for this operation. ```APIDOC ## GET /api/share/id/:shareId ### Description Get shared resource by share ID. ### Method GET ### Endpoint /api/share/id/:shareId ### Parameters #### Path Parameters - **shareId** (string) - Required - The unique ID of the shared resource. ### Response #### Success Response (200) - Shared resource data ``` -------------------------------- ### Get Shared Resource by Slug Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves a shared resource using its unique slug. Authentication is not required for this operation. ```APIDOC ## GET /api/share/:slug ### Description Get shared resource by share slug. ### Method GET ### Endpoint /api/share/:slug ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug of the shared resource. ### Response #### Success Response (200) - Shared resource data based on share type ``` -------------------------------- ### GET /api/websites/:websiteId/sessions/:sessionId Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves a specific session by its ID, including all associated events. Requires authentication. ```APIDOC ## GET /api/websites/:websiteId/sessions/:sessionId ### Description Get a specific session with all events. ### Method GET ### Endpoint /api/websites/:websiteId/sessions/:sessionId ### Response #### Success Response (200) - **sessionId** (string) - The ID of the session - **distinctId** (string) - The distinct ID of the visitor - **createdAt** (string) - The creation timestamp of the session (ISO datetime) - **hostname** (string) - The hostname of the website - **browser** (string) - The browser used by the visitor - **os** (string) - The operating system used by the visitor - **device** (string) - The device used by the visitor - **country** (string) - The country of the visitor - **events** (array) - An array of events within the session #### Response Example ```json { "sessionId": "uuid", "distinctId": "visitor-id", "createdAt": "2023-10-27T10:00:00Z", "hostname": "example.com", "browser": "Chrome", "os": "Windows", "device": "Desktop", "country": "US", "events": [] } ``` ``` -------------------------------- ### Authentication and Authorization Library Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Utilities for handling authentication, authorization, and session management within Umami. ```APIDOC ## Authentication Library (`api-reference/auth.md`) ### Description Provides functions for managing authentication tokens, verifying user credentials, and checking permissions. ### Functions - **`getBearerToken()`** - Description: Extracts the Bearer token from request headers. - Usage: `getBearerToken(req)` - **`checkAuth()`** - Description: Verifies the authentication status of a request. - Usage: `checkAuth(req)` - **`saveAuth()`** - Description: Creates a new user session. - Usage: `saveAuth(user)` - **`hasPermission()`** - Description: Checks if a user has the required permissions for an action. - Usage: `hasPermission(user, permission)` - **`parseShareToken()`** - Description: Validates and parses share tokens for public access. - Usage: `parseShareToken(token)` ### Concepts - Role-based access control (RBAC) ``` -------------------------------- ### GET /api/websites/:websiteId/sessions Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Lists website sessions with filtering options for browser, OS, and country. Supports pagination. ```APIDOC ## GET /api/websites/:websiteId/sessions ### Description List sessions with filtering. ### Method GET ### Endpoint /api/websites/:websiteId/sessions ### Parameters #### Query Parameters - **startAt** (number) - Optional - Start timestamp - **endAt** (number) - Optional - End timestamp - **page** (number) - Optional - Page number - **pageSize** (number) - Optional - Records per page - **browser** (string) - Optional - Filter by browser - **os** (string) - Optional - Filter by OS - **country** (string) - Optional - Filter by country ### Response #### Success Response (200) - **data** (array) - Array of session data - **count** (number) - Total count of sessions - **page** (number) - Current page number #### Response Example ```json { "data": [], "count": 200, "page": 1 } ``` ``` -------------------------------- ### POST /api/auth/logout Example Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md This endpoint invalidates the current session and removes authentication. It requires a bearer token for authentication. ```javascript // No specific code example provided in source, but the endpoint exists. ``` -------------------------------- ### ok() Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/request-response.md Returns a successful empty response with a 200 status code. ```APIDOC ## ok() ### Description Return successful empty response. ### Returns JSON response with `{ ok: true }` ### Status 200 ### Example ```javascript export async function POST(request) { // Process something return ok(); } ``` ``` -------------------------------- ### Payload Too Large Response Example (JSON) Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Response indicating that the request body exceeds the allowed size limit. ```json { "error": { "message": "Payload too large", "code": "payload-too-large", "status": 413 } } ``` -------------------------------- ### Grant CREATE DATABASE Permission Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Ensure the database user has CREATE DATABASE permissions. This is necessary for certain Umami operations. ```bash psql -U postgres -d template1 -c "ALTER USER umami CREATEDB;" ``` -------------------------------- ### Handling Bad Request Errors in JavaScript Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Example of how to handle a bad request error returned from a parsing function. ```javascript const { error } = await parseRequest(request, schema); if (error) { return error(); } ``` -------------------------------- ### Validating and Saving Custom Data Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/data.md Illustrates how to create key-value pairs for custom data, format their values for storage using `getStoredStringValue`, and handle potential array size limits. Requires `createKeyValue` and `getStoredStringValue` imports. ```javascript import { createKeyValue, getStoredStringValue } from '@/lib/data'; const customData = { customField: 'value', count: 123, tags: ['tag1', 'tag2'] }; for (const [key, value] of Object.entries(customData)) { const kv = createKeyValue(key, value); const stored = getStoredStringValue(String(kv.value), kv.dataType); if (stored === null && kv.dataType === DATA_TYPE.array) { console.warn(`Array too large: ${key}`); } else { await saveProperty(key, stored, kv.dataType); } } ``` -------------------------------- ### Get User Journey Data Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Fetches user journey data, including paths and transitions between pages. Requires authentication. ```APIDOC ## POST /api/reports/journey ### Description Get user journey data. ### Method POST ### Endpoint /api/reports/journey ### Response #### Success Response (200) Journey paths and transitions ``` -------------------------------- ### Get Breakdown Analysis Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Performs a breakdown analysis by property values for a given website. Requires authentication and specific parameters. ```APIDOC ## POST /api/reports/breakdown ### Description Get breakdown analysis by property. ### Method POST ### Endpoint /api/reports/breakdown ### Parameters #### Request Body - **websiteId** (string) - Required - Website ID - **parameters** (object) - Required - Query parameters - **filters** (array) - Required - Filter array ### Response #### Success Response (200) Breakdown data by property values ``` -------------------------------- ### Get Attribution Data Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Fetches attribution data for conversions, broken down by traffic source. Requires authentication and specific parameters. ```APIDOC ## POST /api/reports/attribution ### Description Get attribution data for conversions. ### Method POST ### Endpoint /api/reports/attribution ### Parameters #### Request Body - **websiteId** (string) - Required - Website ID - **parameters** (object) - Required - Date range and filters - **filters** (array) - Optional - Additional filters ### Response #### Success Response (200) Attribution data by traffic source ``` -------------------------------- ### Test PostgreSQL Connection Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Verify that Umami can connect to your PostgreSQL database. This command checks the database URL format and ensures PostgreSQL is running. ```bash psql $DATABASE_URL -c "SELECT 1" ``` -------------------------------- ### Get Current User API Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Retrieve information about the currently authenticated user. Requires a Bearer token in the Authorization header. ```bash GET /api/me Authorization: Bearer ``` -------------------------------- ### Run Umami Docker Container with Environment Variables Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Set environment variables using the -e flag when running the Umami Docker container. This includes database connection details and application secrets. ```bash docker run \ -e DATABASE_URL=postgresql://user:pass@postgres:5432/umami \ -e APP_SECRET=your-secret \ -p 3000:3000 \ umami-software/umami:latest ``` -------------------------------- ### Authentication and SSO Configuration Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Disable username/password login to enforce SSO, and configure Google OAuth client ID and secret for single sign-on. ```bash DISABLE_LOGIN=true GOOGLE_CLIENT_ID=your-google-client-id GOOGLE_CLIENT_SECRET=your-google-client-secret ``` -------------------------------- ### GET /api/websites/:websiteId/event-data Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves event property data with filtering and pagination capabilities. Allows searching for specific event properties. ```APIDOC ## GET /api/websites/:websiteId/event-data ### Description Get event property data with filtering and pagination. ### Method GET ### Endpoint /api/websites/:websiteId/event-data ### Parameters #### Query Parameters - **startAt** (number) - Optional - Start timestamp - **endAt** (number) - Optional - End timestamp - **page** (number) - Optional - Page number - **pageSize** (number) - Optional - Records per page - **search** (string) - Optional - Search filter ### Response #### Success Response (200) - **data** (array) - Array of event property data - **count** (number) - Total count of records - **page** (number) - Current page number - **pageSize** (number) - Records per page #### Response Example ```json { "data": [], "count": 50, "page": 1, "pageSize": 10 } ``` ``` -------------------------------- ### S3 File Storage Configuration Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Configure connection details for S3-compatible storage, including URL, access keys, region, and bucket name. ```bash S3_URL=your-s3-url S3_ACCESS_KEY=your-access-key S3_SECRET_KEY=your-secret-key S3_REGION=your-region S3_BUCKET=your-bucket-name ``` -------------------------------- ### Create Feature Branch from Dev Source: https://github.com/umami-software/umami/blob/master/CONTRIBUTING.md Fork the repository and create your feature branch from the 'dev' branch before making changes. ```bash git checkout dev git pull origin dev git checkout -b my-feature ``` -------------------------------- ### Create MD5 Hash (Legacy) Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/crypto.md Provides legacy MD5 hashing for backward compatibility. Use `hash()` for new security-sensitive operations as MD5 is cryptographically broken. ```typescript function md5(...args: string[]): string ``` ```javascript const legacyId = md5(userId, email); ``` -------------------------------- ### Get Funnel Analysis Data Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves funnel analysis data, showing conversion rates through defined funnel steps. Requires authentication. ```APIDOC ## POST /api/reports/funnel ### Description Get funnel analysis data. ### Method POST ### Endpoint /api/reports/funnel ### Parameters #### Request Body - **websiteId** (string) - Required - Website ID - **parameters** (object) - Required - Funnel steps configuration - **filters** (array) - Required - Additional filters ### Response #### Success Response (200) Funnel conversion data ``` -------------------------------- ### Get Application Secret Key Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/crypto.md Retrieves the hashed application secret key. It uses the `APP_SECRET` environment variable or falls back to `DATABASE_URL`. ```typescript function secret(): string ``` ```javascript const appSecret = secret(); const token = createSecureToken(payload, appSecret); ``` -------------------------------- ### Generate Time-Based Salt Source: https://github.com/umami-software/umami/blob/master/_autodocs/api-reference/crypto.md Derives a salt based on the start of a specified time period ('day', 'week', or 'month'). Used for time-sensitive security operations. ```typescript function getSalt(saltRotation: string, createdAt: Date): string ``` ```javascript const daySalt = getSalt('day', new Date()); // Changes every day at midnight const monthSalt = getSalt('month', createdAt); // Changes on first of each month ``` -------------------------------- ### Create a new team Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Creates a new team with the provided name. Authentication is required. ```APIDOC ## POST /api/teams ### Description Create a new team. ### Method POST ### Endpoint /api/teams ### Authentication Required ### Request Body #### Request Body - **name** (string) - Required - Team name ### Response #### Success Response (200) - **id** (string) - Description - **name** (string) - Description - **createdAt** (string) - Description ``` -------------------------------- ### Get User Retention Analysis Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves user retention analysis, providing cohort data to understand user stickiness over time. Requires authentication. ```APIDOC ## POST /api/reports/retention ### Description Get user retention analysis. ### Method POST ### Endpoint /api/reports/retention ### Response #### Success Response (200) Retention cohort data ``` -------------------------------- ### GET /api/websites/:websiteId/realtime/:websiteId Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Fetches real-time analytics data, including pageviews, visitors, and events. Authentication is required or a share token can be used. ```APIDOC ## GET /api/websites/:websiteId/realtime/:websiteId ### Description Get real-time analytics updates. ### Method GET ### Endpoint /api/websites/:websiteId/realtime/:websiteId ### Response #### Success Response (200) - Real-time data snapshot with pageviews, visitors, events, countries #### Response Example ```json { "pageviews": { "value": 50, "change": 5 }, "visitors": { "value": 20, "change": 2 }, "events": [], "countries": { "US": 10, "CA": 5, "GB": 5 } } ``` ``` -------------------------------- ### POST /api/auth/login Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Authenticates a user with provided credentials and returns an authentication token upon success. ```APIDOC ## POST /api/auth/login ### Description Authenticate a user and receive an authentication token. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body - **username** (string) - Required - Username - **password** (string) - Required - Password ### Response #### Success Response (200) - **token** (string) - **user** (object) - Contains user details like id, username, role, createdAt, isAdmin, teams #### Error Response - **401**: Invalid credentials (code: `incorrect-username-password`) ### Request Example ```javascript const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'password' }) }); const { token } = await response.json(); ``` ``` -------------------------------- ### Get Website Metrics API Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Fetch analytics metrics for a specific website within a given time range and unit. Requires a Bearer token. ```bash GET /api/websites//metrics?startAt=&endAt=&unit=day Authorization: Bearer ``` -------------------------------- ### DateParams Interface Source: https://github.com/umami-software/umami/blob/master/_autodocs/types.md Specifies parameters related to date ranges and timezones for queries. Includes start and end dates, unit, timezone, and an optional comparison date. ```typescript interface DateParams { startDate?: Date; endDate?: Date; unit?: string; timezone?: string; compareDate?: Date; } ``` -------------------------------- ### Umami API Authentication Source: https://github.com/umami-software/umami/blob/master/_autodocs/README.md Obtain an API Bearer token by logging in with username and password. Use this token in the Authorization header for subsequent API requests. ```bash # Login to get token curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"username":"admin","password":"umami"}' # Use token in requests curl http://localhost:3000/api/me \ -H "Authorization: Bearer " ``` -------------------------------- ### GET /api/websites/:websiteId/events Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Lists page views and custom events for a given website. Supports filtering by time range, URL, and event name, with pagination. ```APIDOC ## GET /api/websites/:websiteId/events ### Description List page views and custom events. ### Method GET ### Endpoint /api/websites/:websiteId/events ### Parameters #### Query Parameters - **startAt** (number) - Optional - Start timestamp - **endAt** (number) - Optional - End timestamp - **url** (string) - Optional - Filter by URL - **event** (string) - Optional - Filter by event name - **page** (number) - Optional - Page number - **pageSize** (number) - Optional - Records per page ### Response #### Success Response (200) - **data** (array) - Array of event data - **count** (number) - Total count of events - **page** (number) - Current page number #### Response Example ```json { "data": [], "count": 100, "page": 1 } ``` ``` -------------------------------- ### Error Response Propagation Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Error handlers return functions that can be called to generate responses. This example shows how to call the returned error function to propagate an error. ```javascript const { error } = await parseRequest(request); if (error) { return error(); // Calls the error function } ``` -------------------------------- ### Application Secret Key Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Configure a secret key for token signing and encryption. For production, use a strong, random value. ```bash APP_SECRET=your-super-secret-random-string-here ``` -------------------------------- ### Import Vitest APIs Source: https://github.com/umami-software/umami/blob/master/src/test/README.md Explicitly import Vitest APIs for clarity and to avoid potential naming conflicts. ```typescript import { describe, expect, test, vi } from 'vitest'; ``` -------------------------------- ### CSV Formula Injection Prevention Source: https://github.com/umami-software/umami/blob/master/_autodocs/errors.md Umami prevents CSV formula injection by rejecting values that start with common spreadsheet formula triggers. This defense mechanism is applied during analytics exports. ```text Values starting with =, +, -, @, tab, or carriage return ``` -------------------------------- ### MaxMind GeoIP2 License Key Source: https://github.com/umami-software/umami/blob/master/_autodocs/configuration.md Provide the MaxMind GeoIP2 license key for geo-location detection. If not provided, a local GeoIP database is used. ```bash MAXMIND_LICENSE_KEY=your-maxmind-license-key ``` -------------------------------- ### List Websites Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves a list of websites accessible to the current user, with pagination support. ```APIDOC ## GET /api/websites ### Description List websites for the current user. ### Method GET ### Endpoint /api/websites ### Query Parameters - **page** (number) - Optional - Page number - **pageSize** (number) - Optional - Records per page ### Response #### Success Response (200) - **id** (string) - Website ID - **name** (string) - Website name - **domain** (string) - Website domain - **teamId** (string) - Team ID - **userId** (string) - User ID - **createdAt** (string) - Creation timestamp ### Response Example { "example": "[ { \"id\": \"1\", \"name\": \"My Website\", \"domain\": \"example.com\", \"teamId\": \"1\", \"userId\": \"1\", \"createdAt\": \"2023-01-01T12:00:00.000Z\" } ]" } ``` -------------------------------- ### GET /api/websites/:websiteId/metrics Source: https://github.com/umami-software/umami/blob/master/_autodocs/endpoints.md Retrieves aggregated website metrics including pageviews, visitors, bounce rate, and session duration. Supports filtering by time range and unit, and timezone grouping. ```APIDOC ## GET /api/websites/:websiteId/metrics ### Description Get aggregated website metrics. ### Method GET ### Endpoint /api/websites/:websiteId/metrics ### Parameters #### Query Parameters - **startAt** (number) - Optional - Start timestamp (ms) - **endAt** (number) - Optional - End timestamp (ms) - **unit** (string) - Optional - Time unit (year, month, day, hour) - **timezone** (string) - Optional - Timezone for grouping ### Response #### Success Response (200) - **pageviews** (object) - Object containing value and change for pageviews - **visitors** (object) - Object containing value and change for visitors - **bounce_rate** (object) - Object containing value and change for bounce rate - **session_duration** (object) - Object containing value and change for session duration #### Response Example ```json { "pageviews": { "value": 1000, "change": 10 }, "visitors": { "value": 500, "change": 5 }, "bounce_rate": { "value": 0.5, "change": -0.02 }, "session_duration": { "value": 120, "change": 10 } } ``` ```