# Set up Lantern in two lines

> For the complete documentation index, see [llms.txt](https://visitlantern.com/llms.txt). This page is the Markdown version of https://visitlantern.com/docs.

One rewrite on your host and one script tag, or one prompt to your coding agent. Lantern starts counting visitors, sources, AI referrals and goals within a minute, with nothing else to configure.

The examples use the site id `site_xxxxxxxxxxxx` and the domain `yourdomain.com`. Replace them with your own: the site id is in the Lantern dashboard, in the site's Install panel.

## Set up with an AI agent

The fastest way: let your coding agent (Claude Code, Codex, Cursor, or any agent that can edit your repository) do the install. It adds the rewrite and the script for your framework, then reads your code to find your main KPI, the funnel leading to it and the first actions that show a user is activated, and instruments those goals where they actually succeed. Nothing to name or configure in Lantern; goals show up as soon as they fire.

Copy the prompt from your site's Install panel (it has your site id filled in), or use this one:

```
Set up Lantern analytics in this project and instrument its key goals.
Site ID: site_xxxxxxxxxxxx
Domain: yourdomain.com
Follow the instructions at https://visitlantern.com/setup.md?site=site_xxxxxxxxxxxx&domain=yourdomain.com
```

The agent writes `lantern-tracking-plan.md` with the goals and funnels it added, so you can review every event before you deploy. It doesn't commit or deploy unless you ask.

Agent without web access? The instructions are plain Markdown at [https://visitlantern.com/setup.md](https://visitlantern.com/setup.md); paste them in directly.

### Claude Code skill

Install it once and set up any project with a single command:

```sh
mkdir -p ~/.claude/skills/lantern-setup && curl -fsSL https://visitlantern.com/skill.md -o ~/.claude/skills/lantern-setup/SKILL.md
```

Then, in Claude Code in your project:

```
/lantern-setup site site_xxxxxxxxxxxx on yourdomain.com
```

## Install manually

Add a site in the dashboard to get its `data-site` id; the install panel there shows these snippets with your id filled in. Pick your host:

### Next.js

1. Add the rewrite (`next.config.ts`):

```
const nextConfig = {
  async rewrites() {
    return [{ source: "/_p/:path*", destination: "https://api.visitlantern.com/:path*" }];
  },
};
```

2. Add the script (app/layout.tsx):

```
import Script from "next/script";

// inside <body>
<Script src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com" strategy="afterInteractive" />
```

Already have rewrites? Add the one entry to your existing array.

### Next.js on Cloudflare

1. Add the rewrite (`proxy.ts (middleware.ts before Next.js 16), next to app/`):

```
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const url = new URL(request.nextUrl.pathname.slice(3) + request.nextUrl.search, "https://api.visitlantern.com");
  const headers = new Headers(request.headers);
  const ip = request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for");
  if (ip) headers.set("x-forwarded-for", ip);
  return NextResponse.rewrite(url, { request: { headers } });
}

export const config = { matcher: "/_p/:path*" };
```

2. Add the script (app/layout.tsx):

```
import Script from "next/script";

// inside <body>
<Script src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com" strategy="afterInteractive" />
```

For Next.js deployed to Cloudflare with OpenNext. Its next.config rewrite drops the visitor's IP, which puts every visitor at Cloudflare's servers in Portland; this passes it on. Already have a proxy or middleware? Add the /_p branch to it.

### Vercel

1. Add the rewrite (`vercel.json`):

```
{
  "rewrites": [{ "source": "/_p/:path*", "destination": "https://api.visitlantern.com/:path*" }]
}
```

2. Add the script (index.html, inside <head>):

```
<script defer src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com"></script>
```

For any framework deployed on Vercel (Astro, SvelteKit, Vite, Remix…). On Next.js, use the Next.js tab.

### Netlify

1. Add the rewrite (`public/_redirects`):

```
/_p/*  https://api.visitlantern.com/:splat  200
```

2. Add the script (index.html, inside <head>):

```
<script defer src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com"></script>
```

The 200 makes it a rewrite (proxy), not a redirect. Put the file in the folder Netlify publishes.

### Cloudflare

1. Add the rewrite (`Worker, on the route yourdomain.com/_p/*`):

```
export default {
  async fetch(request) {
    const url = new URL(request.url);
    const upstream = new Request("https://api.visitlantern.com" + url.pathname.slice(3) + url.search, request);
    upstream.headers.set("X-Forwarded-For", request.headers.get("CF-Connecting-IP") ?? "");
    return fetch(upstream);
  },
};
```

2. Add the script (index.html, inside <head>):

```
<script defer src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com"></script>
```

For sites behind Cloudflare. Forwarding CF-Connecting-IP keeps visitor locations accurate.

### nginx

1. Add the rewrite (`server { … }`):

```
location /_p/ {
    proxy_pass https://api.visitlantern.com/;
    proxy_ssl_server_name on;
    proxy_set_header Host api.visitlantern.com;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```

2. Add the script (index.html, inside <head>):

```
<script defer src="/_p/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com"></script>
```

### Other

Add the script (inside <head>):

```
<script defer src="https://api.visitlantern.com/script.js" data-site="site_xxxxxxxxxxxx" data-domain="yourdomain.com"></script>
```

Works anywhere, with no server changes. Ad blockers will hide some visitors, so add a rewrite later if your host supports one.

That's the whole setup. Deploy, open your site, and the visit shows up on the dashboard and the live globe within seconds.

## Why a rewrite

Ad blockers and privacy browsers (uBlock Origin, Brave, Safari's tracking protection) block scripts from known analytics domains. On sites with a technical audience that's often 20–40% of visitors, and they vanish from your numbers without any error.

The rewrite serves Lantern from `yourdomain.com/_p`, which is your own domain, so there's nothing to block. The script sends its events back through the same path, so the one rule covers both. Visitor locations stay accurate: your host forwards the visitor's IP, and Lantern uses it only to look up the city.

`/_p` is a suggestion; any unused path works if you change it in both the rewrite and the script's `src`.

## Check it works

After adding the site, the dashboard's install panel waits for your first pageview and confirms it. It also tells you whether the script is being served from your domain, so you know the rewrite works.

To check by hand, open your site with the browser's developer tools on the Network tab:

| Request | Expect |
|---|---|
| `/_p/script.js` | 200, JavaScript (not your site's HTML or a 404: that means the rewrite isn't active yet) |
| `/_p/api/event` | 202 for each pageview |

Visits from `localhost` and from domains other than your site's are ignored, so local development and preview deployments on another domain don't pollute your numbers. Subdomains of your site, like `app.yourdomain.com`, are counted.

## Goals and events

Pageviews, sources, time on page and scroll depth are automatic. Track the moments that matter to your business as goals; they show up in the Goals card and on the live globe.

There's nothing to install or import. The script tag you added puts one function on the page, `window.lantern`, and you call it from code that runs in the browser: a click handler, a form's success callback, a `useEffect`. Write it as `window.lantern?.(…)` so it's safe while the script is still loading and during server rendering.

```js
// No import: the Lantern script tag adds window.lantern to every page.
// Call it from browser code: an event handler, a success callback, an effect.
window.lantern?.("track", "signup", { plan: "pro" })

// After sign-in: tie this visitor to your user
window.lantern?.("identify", user.id)

// Or without JavaScript: count clicks on any element
<button data-lantern-goal="signup_click" data-lantern-plan="pro">Sign up</button>
```

In Next.js, call it from a client component (`"use client"`), never from a server component, route handler or server action: those run on your server, where there's no `window`. Using TypeScript? Add this declaration once, so `window.lantern` type-checks:

```ts
// types/lantern.d.ts
declare global {
  interface Window {
    lantern?: ((cmd: "track" | "identify", ...args: unknown[]) => void) & { visitorId?: () => string };
  }
}
export {};
```

Event names are up to 120 characters; each event takes up to 30 properties with string, number or boolean values. To call `lantern()` before the script has loaded (for example, from inline code at the top of the page), add the queue stub first, in `<head>` before your own code:

```html
<script>window.lantern = window.lantern || function () { (lantern.q = lantern.q || []).push(arguments) };</script>
```

## Identify users

Visitors are anonymous. When someone signs in or signs up, call `identify` with your own user id. Their visits from then on carry that id, alongside the anonymous visitor id from before, so you can trace what first brought each customer.

```js
window.lantern?.("identify", user.id, { plan: "pro" })
```

Use an internal id rather than an email address, so no personal data is sent to Lantern.

## Revenue

Connect your payment provider in the site's **Settings → Revenue**: Stripe, Dodo Payments, Paddle, Polar, Lemon Squeezy, Razorpay or Cashfree. Lantern credits every payment, renewal and refund to the channel, referrer, campaign, country and landing page that first brought that customer, even when they bought days later.

Stripe, Dodo, Paddle and Polar take a read-only key, which also imports your last 90 days. Lemon Squeezy, Razorpay and Cashfree keys can't be limited, so those connect with a webhook, and a key is optional.

To link a payment to its visit, send the visitor id to your server and add it to the checkout:

```js
// Browser: send window.lantern.visitorId() along with the checkout request.
const session = await stripe.checkout.sessions.create({
  // …your line items
  metadata: { lantern_visitor_id: visitorId, lantern_user_id: user.id },
  subscription_data: { metadata: { lantern_visitor_id: visitorId, lantern_user_id: user.id } },
});
```

The same two keys go in `metadata` on Dodo and Polar, `customData` on Paddle, `checkout[custom]` on Lemon Squeezy, `notes` on Razorpay and `order_tags` on Cashfree. `lantern_user_id` is the id you pass to `identify`, which also links payments that carry no visitor id. Renewals and refunds follow the original payment on their own.

## Subdomains

With `data-domain="yourdomain.com"` on the script (the install snippet includes it), the visitor id is stored in a cookie shared by all your subdomains. Someone who reads your blog on `yourdomain.com` and signs up on `app.yourdomain.com` is counted as one person with one source. Add the same script, with the same `data-site`, on every subdomain.

## Single-page apps

Client-side navigation in Next.js, React Router, Vue Router, SvelteKit and similar is tracked automatically: Lantern listens to the browser's history changes and records a pageview for each new URL. No router integration is needed.

## AI crawlers

GPTBot, ClaudeBot, PerplexityBot and other crawlers never run JavaScript, so the script can't see them. To find out which pages AI tools read, report crawler requests from your server. The install panel in the dashboard has a ready-made Next.js snippet with your site's secret; for other servers, send requests from crawler user agents to:

```http
POST https://api.visitlantern.com/api/bot
Authorization: Bearer <your site's bot secret>
Content-Type: application/json

{ "ua": "<user-agent>", "url": "<full page URL>", "ip": "<client IP>" }
```

Up to 500 hits per request as a JSON array. Human user agents are ignored, so it's safe to over-send.

## Ask your AI assistant (MCP)

Lantern runs an MCP server, so Claude, Codex, Cursor, VS Code and other AI assistants can answer questions about your sites: how this week compares with last, which channels brought paying customers, where visitors drop off in a funnel, which pages AI assistants send people to. It reads the same numbers as your dashboard and can't change anything.

In Claude (web, desktop and mobile), add Lantern from Claude's connectors directory at https://claude.ai/directory/connectors/lantern-analytics, click Connect and sign in to Lantern. No key needed. (Or add it by hand: Settings → Connectors → Add custom connector, paste `https://visitlantern.com/api/mcp`.) For other assistants, create an API key at https://visitlantern.com/dashboard/mcp (in the menu under your avatar), which also has the setup for each assistant with your key filled in. Connected apps and keys can be disconnected on the same page. Tools: list_sites, get_overview, get_timeseries, get_breakdown, get_event_properties, get_realtime, get_revenue, get_ai_crawlers, get_funnels, run_funnel.

### Claude Code

```sh
claude mcp add --transport http --scope user lantern https://visitlantern.com/api/mcp --header "Authorization: Bearer YOUR_LANTERN_API_KEY"
```

--scope user makes Lantern available in every project. Run /mcp in Claude Code to check it's connected. The same command works in PowerShell on Windows.

### Codex

In `~/.codex/config.toml`:

```toml
[mcp_servers.lantern]
url = "https://visitlantern.com/api/mcp"
bearer_token_env_var = "LANTERN_API_KEY"

# Then set the key, once.
# Mac or Linux, in ~/.zshrc or ~/.bashrc:
#   export LANTERN_API_KEY="YOUR_LANTERN_API_KEY"
# Windows, in PowerShell:
#   setx LANTERN_API_KEY "YOUR_LANTERN_API_KEY"
```

Codex reads the key from the LANTERN_API_KEY environment variable. On Windows the file is %USERPROFILE%\.codex\config.toml. Open a new terminal and restart Codex after saving; the CLI and the IDE extension share this file.

### Cursor

In `~/.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "lantern": {
      "url": "https://visitlantern.com/api/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_LANTERN_API_KEY"
      }
    }
  }
}
```

On Windows the file is %USERPROFILE%\.cursor\mcp.json. Already have MCP servers? Add the lantern entry to your existing mcpServers.

### VS Code

In `.vscode/mcp.json`:

```json
{
  "servers": {
    "lantern": {
      "type": "http",
      "url": "https://visitlantern.com/api/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_LANTERN_API_KEY"
      }
    }
  }
}
```

For GitHub Copilot's agent mode. Put it in your user settings' mcp.json to use it in every workspace.

### Any other client

Connect to `https://visitlantern.com/api/mcp` over Streamable HTTP. Clients that support MCP's OAuth sign-in discover it automatically; others send the header `Authorization: Bearer <your key>`. A key reads every site in your account; delete it on the same page to cut off access.

## Script attributes

| Attribute | Description |
|---|---|
| `data-site` | Required. Your site id from the dashboard. |
| `data-domain` | Your root domain. Shares the visitor id across subdomains. |
| `data-api` | Where to send events. Defaults to wherever the script was loaded from, so you only need it for unusual proxy setups. |
| `data-allow-local` | Run on localhost. Only useful with a local Lantern server; the hosted service ignores localhost. |

## JavaScript API

| Call | Description |
|---|---|
| `lantern("track", name, props?)` | Records a goal or custom event. |
| `lantern("identify", userId, traits?)` | Links this visitor to your user id. |
| `lantern("revenue", amount, currency?, props?)` | Records a purchase seen in the browser, as a goal. For revenue by channel, connect your payment provider instead. |
| `lantern.visitorId()` | The anonymous visitor id, for checkout metadata (`lantern_visitor_id`). |
| `data-lantern-goal="name"` | On any element: records the goal when it's clicked. Other `data-lantern-*` attributes become properties. |

Installed Lantern before it was renamed? `window.pulse` and `data-pulse-*` are the same API under the old name and keep working, so there's nothing to change.

## Privacy and data

- One first-party cookie, `_pulse_vid`, holds a random visitor id on your own domain. There are no third-party cookies and no tracking across other websites.
- IP addresses are used once, when the event arrives, to look up the city and network, and are never stored. Locations are approximate (mobile carriers in particular often resolve to a nearby city).
- Automated browsers are skipped, and known bots are kept out of visitor counts.
- Events are stored on Google Cloud in the United States.

IP geolocation by [DB-IP](https://db-ip.com).

## Troubleshooting

| Symptom | Fix |
|---|---|
| No visits at all | Open `yourdomain.com/_p/script.js`. If it isn't JavaScript, the rewrite isn't deployed yet. Also check that `data-site` matches the dashboard and the site's domain matches where the script runs. |
| Works locally, nothing in production | Localhost is ignored by design. Test on your deployed site, or on a subdomain of it. |
| Fewer visitors than expected | You're probably loading the script from our domain. Add the rewrite so ad blockers don't hide visitors. |
| Blocked by Content Security Policy | With the rewrite, `'self'` already covers Lantern. Without it, add `https://api.visitlantern.com` to `script-src` and `connect-src`. |
