Skip to content

Instantly share code, notes, and snippets.

@cofob
Last active June 28, 2025 18:53
Show Gist options
  • Select an option

  • Save cofob/e0c9e8fd51a8b1c456b5441051251d9e to your computer and use it in GitHub Desktop.

Select an option

Save cofob/e0c9e8fd51a8b1c456b5441051251d9e to your computer and use it in GitHub Desktop.

Cloudflare Link Shortener with D1 and OIDC Authentication

A powerful, secure, and serverless link shortener built to run on the Cloudflare network, featuring Cloudflare Workers, a D1 database, and robust OpenID Connect (OIDC) authentication. This project provides a complete solution for creating, managing, and tracking short URLs with a secure admin interface.

Features

  • Serverless Architecture: Runs entirely on Cloudflare's global network, ensuring high performance and scalability with no servers to manage.
  • Flexible & Secure Authentication:
    • OpenID Connect (OIDC): Modern, standard-based authentication for secure login. Integrate with any OIDC-compliant provider (e.g., Google, Okta, Auth0).
    • Secret Token: A simple, backward-compatible secret token method is also available.
  • Secure Admin Panel: Link management (create, update, delete) is restricted to authenticated users.
  • Persistent Storage: Uses Cloudflare's native D1 database to store links and logs.
  • Complete Audit Trail: All create, update, and delete actions are logged to a separate D1 table. When using OIDC, the authenticated user's identity is recorded with each action.
  • Dynamic Redirection: Handles short link resolution and redirects users to the original long URL.
  • Easy Deployment: A single-file worker script and a simple configuration make setup and deployment straightforward.

Technology Stack


Setup and Deployment

Follow these steps to get your link shortener up and running.

1. Prerequisites

  • A Cloudflare account.
  • An OpenID Connect application set up with your chosen provider (e.g., Google, Okta). You will need the Client ID, Client Secret, and the Provider's URL.
    • When configuring your OIDC application, set the Redirect URI (or Callback URL) to: https://go.f0rth.space/auth/oidc/callback
  • Node.js and npm installed.
  • The Wrangler CLI installed and authenticated:
    npm install -g wrangler
    wrangler login

2. Project Files

Create a project directory and place the worker script (index.js) inside.

3. Configure wrangler.toml

Create a wrangler.toml file in your project's root directory with the following content.

name = "link-shortener-oidc"
main = "index.js"
compatibility_date = "2024-01-01" # Or a more recent date

# D1 Database Binding
[[d1_databases]]
binding = "DB"
database_name = "link-shortener-db"
database_id = "" # This will be filled in a later step

# OIDC and Secret Token variables will be set as secrets
[vars]
# No secrets should be stored here directly.
# We will add them using the `wrangler secret` command.

4. Create the D1 Database

In your terminal, run the following command to create the D1 database:

wrangler d1 create link-shortener-db

This command will output the database_id. Copy it and paste it into the database_id field in your wrangler.toml file.

5. Configure Secrets

For security, your OIDC credentials and secret token must be stored as encrypted secrets, not in plain text in wrangler.toml. Run the following commands in your terminal, replacing the placeholder values with your actual credentials.

# OIDC Provider URL (e.g., https://accounts.google.com or https://your-domain.okta.com)
wrangler secret put OIDC_PROVIDER_URL
# Paste your provider's URL when prompted

# OIDC Client ID from your provider
wrangler secret put OIDC_CLIENT_ID
# Paste your Client ID when prompted

# OIDC Client Secret from your provider
wrangler secret put OIDC_CLIENT_SECRET
# Paste your Client Secret when prompted

# A securely generated random string for the legacy authentication method
wrangler secret put SECRET_TOKEN
# Paste your secret token when prompted

6. Define and Apply the Database Schema

Create a schema.sql file with the table definitions:

-- Remove tables if they exist to ensure a clean slate
DROP TABLE IF EXISTS links;
DROP TABLE IF EXISTS logs;

-- Create the table for storing short links
CREATE TABLE links (
  slug TEXT PRIMARY KEY,
  url TEXT NOT NULL,
  created_at TEXT NOT NULL
);

-- Create the table for logging all actions
CREATE TABLE logs (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  action TEXT NOT NULL,
  slug TEXT NOT NULL,
  details TEXT,
  timestamp TEXT NOT NULL
);

Execute this schema against your newly created database:

wrangler d1 execute link-shortener-db --file=schema.sql

7. Deploy the Worker

Finally, deploy your application to the Cloudflare network:

wrangler deploy

Your link shortener is now live!


Usage

1. Authenticate Yourself

Navigate to your worker's root URL: https://go.f0rth.space/

You will be presented with a login page. You have two ways to authenticate.

Method 1: OpenID Connect (Recommended)

Click the "Login with OpenID Connect" button. You will be redirected to your OIDC provider to sign in. After successful authentication, you will be redirected back to the admin panel. Your user information (subject, email, issuer) will be displayed, and all your actions will be logged with your identity.

Method 2: Secret Token (Legacy)

If you need to bypass OIDC, you can use the secret token method. Open your browser and navigate to:

https://go.f0rth.space/secret/your-super-secret-random-token

  • Replace your-super-secret-random-token with the token you set as the SECRET_TOKEN secret.

You will be automatically redirected to the admin panel.

2. Manage Links

Once authenticated, the root URL will display the management dashboard. From here you can:

  • Create or Update Links: Fill in the slug and destination URL and click "Save Link". If the slug exists, its URL will be updated.
  • View All Links: A table lists all existing short links, their destinations, and creation dates.
  • Delete Links: Click the "Delete" button next to any link to remove it. You will be asked for confirmation.
  • Logout: If you logged in via OIDC, a logout link is available to clear your session.

3. Using Short Links

Share your short links using your worker's URL. For example, a link with the slug blog will be accessible at:

https://go.f0rth.space/ender3

License

This project is licensed under the MIT License.

CREATE TABLE links (
slug TEXT PRIMARY KEY,
url TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action TEXT NOT NULL,
slug TEXT NOT NULL,
details TEXT,
timestamp TEXT NOT NULL
);
CREATE INDEX idx_links_slug ON links (slug);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment