Skip to main content
Generates a cryptographically secure random alphanumeric string.

Signature

sqlpage.random_string(length INTEGER) -> TEXT

Parameters

length
INTEGER
required
The length of the string to generate

Return Value

return
TEXT
A random alphanumeric string of the specified length

Description

The random_string() function generates cryptographically secure random strings suitable for tokens, session IDs, and passwords.

Examples

Generate Session Token

INSERT INTO sessions (user_id, token, expires_at)
VALUES (
    :user_id,
    sqlpage.random_string(32),
    datetime('now', '+7 days')
)
RETURNING
    'cookie' as component,
    'session' as name,
    token as value;

Password Reset Token

INSERT INTO password_resets (email, token, expires_at)
VALUES (
    :email,
    sqlpage.random_string(64),
    datetime('now', '+1 hour')
)
RETURNING
    'Email sent with reset link: /reset?token=' || token as message;

Generate API Key

INSERT INTO api_keys (user_id, key, created_at)
VALUES (
    :user_id,
    sqlpage.random_string(40),
    CURRENT_TIMESTAMP
)
RETURNING
    'alert' as component,
    'API Key Generated' as title,
    'Your API key: ' || key as description;

Build docs developers (and LLMs) love