# Getting started: from signup to your first diagnosed crash

> Set up LAWDE Shield end to end: sign up, run npx @lawdeshield/cli init (or install @lawdeshield/agent by hand for Next.js, Express, Medusa or raw HTTP), see your first event, run a diagnosis and connect GitHub.

Source: https://www.lawde.net/docs/getting-started

This is the whole path in one page. LAWDE does not pull crashes from your servers: your app sends them. Quick setup does the wiring for you; the manual path shows the same code if you would rather write it yourself. If a step fails, the exact message and its fix are in [Troubleshooting](https://www.lawde.net/docs/troubleshooting).

## 1. Sign up

Create an account at [lawde.net/signup](https://www.lawde.net/signup) with GitHub or Google. Your first login creates a Hobby workspace; nothing appears on the dashboard until your app sends an error.

Errors belong to an app inside the workspace. If the workspace has no app yet, create one on [Apps](https://www.lawde.net/apps) first: browser sign-in in the next step asks which app the new key is for.

## 2. Quick setup: npx @lawdeshield/cli init

Run `npx @lawdeshield/cli init` in your app’s folder. It works with Next.js, Express, Node servers and Medusa v2, shows every file change as a diff before writing it, and asks before each one.

Terminal:

```bash
# In your app's folder (Next.js, Express, Node or Medusa v2)
npx @lawdeshield/cli init

# Preview every change without writing, installing or sending anything
npx @lawdeshield/cli init --dry-run
```

What the command does, in order:

1. Prints what it will send: one test error at the end (skip it with `--no-test`), which counts as 1 error toward today’s quota. The CLI sends no file names, paths or code.
2. Detects the framework (Next.js, Express, Medusa v2 or a Node entry file), TypeScript or JavaScript, and your package manager. In a monorepo it asks which package to set up.
3. Gets a key. It uses `--key`, `LAWDE_API_KEY`, or a key already in your env file. Otherwise it shows a code and opens lawde.net: you sign in, check the code matches, pick the app, and approve. LAWDE then creates a new key for that one app. The code expires in 10 minutes and works once. Use `--paste` to paste a key instead, or `--no-browser` to print the link.
4. Installs `@lawdeshield/agent` with your package manager, after asking.
5. Shows each file change as a diff and asks before writing it. Next.js: `instrumentation.ts` with `register()` and `onRequestError`. Express or Node: a new `lawde.js` (or `lawde.ts`) loaded first from your entry file; the Express error handler is printed for you to add after your routes. Medusa v2: `instrumentation.ts` and `src/api/middlewares.ts`. A file that already has its own code is not edited; the CLI prints what to add instead.
6. Writes `LAWDE_API_KEY` (and `LAWDE_APP_ID` when known) to `.env.local` for Next.js or `.env` otherwise, and adds that file to `.gitignore` if git does not ignore it yet.
7. Reminds you that the env file is not deployed. On Vercel it prints `vercel env add LAWDE_API_KEY production`; the CLI never runs it for you.
8. Sends one test error. It prints ✓ only when LAWDE’s response confirms the error was stored, with a link to it. Anything else prints ✗ with the reason.

> **What ✓ means.** ✓ checks your key and app. It does not show that your app reports its own errors: that starts once your app runs with the new code. The test error is tagged as a CLI test, so it never counts as your app’s first real event.

Options:

```text
--dry-run        Show every change as a diff; write, install and send nothing
-y, --yes        Accept every change (for scripts and CI)
--key <key>      API key (or set LAWDE_API_KEY). Without one you approve in the browser
--paste          Paste a key instead of approving in the browser
--no-browser     Print the approval link instead of opening it
--app <id>       App ID (or set LAWDE_APP_ID). Browser sign-in sets it for you
--cwd <dir>      Project folder (default: current folder)
--entry <file>   Server entry file for Express / Node, when it can't be detected
--no-install     Don't install @lawdeshield/agent
--no-test        Don't send the test error
```

## 3. Or set it up by hand

Install the agent, copy a key from [Settings → API keys](https://www.lawde.net/settings/api-keys) (the full value is shown once), and put it in your server environment. Keep the key server-side.

Install:

```bash
npm install @lawdeshield/agent
```

.env:

```bash
LAWDE_API_KEY=lawde_...   # from Settings → API keys (shown once)
LAWDE_APP_ID=...          # optional: the app this key reports to
```

## Next.js (App Router): instrumentation.ts

Next.js catches errors from Route Handlers, Server Components, Server Actions and proxy itself, so they never reach `uncaughtException`. The `onRequestError` hook (Next.js 15+) hands them to LAWDE. Without it, a typical API 500 never reaches LAWDE.

instrumentation.ts:

```ts
// File: instrumentation.ts (project root, or src/ if you use a src directory)
import type { Instrumentation } from 'next';
import type { LawdeAgent } from '@lawdeshield/agent';

let agent: LawdeAgent | undefined;

export async function register() {
  // Runs once when the Next.js server process boots (Node runtime only)
  if (process.env.NEXT_RUNTIME !== 'nodejs') return;
  if (!process.env.LAWDE_API_KEY) {
    console.warn('[LAWDE] LAWDE_API_KEY missing — live crash capture disabled');
    return;
  }
  const { LawdeAgent } = await import('@lawdeshield/agent');
  agent = new LawdeAgent({
    apiKey: process.env.LAWDE_API_KEY,
    appId: process.env.LAWDE_APP_ID,
    // release + environment resolve from LAWDE_RELEASE / LAWDE_ENVIRONMENT,
    // then Vercel's VERCEL_GIT_COMMIT_SHA / VERCEL_ENV automatically.
  });
}

// Next.js catches Route Handler, Server Component, Server Action and proxy errors itself, so
// they never reach process 'uncaughtException'. This hook (Next.js 15+) hands them to LAWDE.
// routePath is the route file pattern (e.g. /app/api/orders/[id]/route), never the real URL.
export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  await agent?.captureException(err, {
    metadata: { route: context.routePath, route_type: context.routeType, method: request.method },
  });
};
```

More options, including source maps: [JavaScript / TypeScript SDK → Next.js](https://www.lawde.net/docs/sdk/javascript#nextjs).

## Express

Create the agent before your app, and register its error handler after your routes.

server.ts:

```ts
import express from 'express';
import { LawdeAgent } from '@lawdeshield/agent';

const agent = new LawdeAgent({ apiKey: process.env.LAWDE_API_KEY! });
const app = express();
// ...your routes
app.use(agent.expressErrorHandler()); // after your routes
app.listen(3000);
```

Fastify, Koa and NestJS adapters: [JavaScript / TypeScript SDK](https://www.lawde.net/docs/sdk/javascript#express).

## Medusa v2

instrumentation.ts:

```ts
// instrumentation.ts (project root, next to medusa-config.ts)
// `medusa start` runs register() once in every process, including cluster workers.
import { initLawde } from '@lawdeshield/agent/medusa';

export function register() {
  // Reads LAWDE_API_KEY and LAWDE_APP_ID. Without a key it logs a warning and sends nothing.
  initLawde();
}
```

src/api/middlewares.ts:

```ts
// src/api/middlewares.ts
import { defineMiddlewares, errorHandler } from '@medusajs/framework/http';
import { lawdeErrorHandler } from '@lawdeshield/agent/medusa';

export default defineMiddlewares({
  // Reports 5xx errors to LAWDE (route pattern, method, status — never the real URL),
  // then Medusa's own handler sends the usual response.
  errorHandler: lawdeErrorHandler(errorHandler()),
  routes: [
    // …your existing middleware routes stay here
  ],
});
```

Environment:

```bash
# Every Medusa host (Medusa's server does not run on Vercel)
LAWDE_API_KEY=lawde_live_…
LAWDE_APP_ID=…            # optional
LAWDE_ENVIRONMENT=production  # not needed on Railway: RAILWAY_ENVIRONMENT_NAME is read
# Release (git SHA) is read automatically on Railway (RAILWAY_GIT_COMMIT_SHA) and
# Render (RENDER_GIT_COMMIT). Elsewhere set LAWDE_RELEASE=<git SHA> at build/deploy time.
# Without a known environment LAWDE cannot judge fixes for this app.
```

Subscribers, scheduled jobs and workflow steps: [JavaScript / TypeScript SDK → Medusa](https://www.lawde.net/docs/sdk/javascript#medusa).

## Any language: raw HTTP

POST JSON to `/api/v1/logs/ingest` with your key in the `x-lawde-api-key` header (`Authorization: Bearer <key>` also works). Required fields: `error_class`, `error_message`, `stack_trace`, `file_path` and `line_number`. Optional: `column_number`, `commit_hash`, `environment`, `timestamp`, `metadata` and `app_id`.

cURL:

```bash
curl -X POST https://www.lawde.net/api/v1/logs/ingest \
  -H "Content-Type: application/json" \
  -H "x-lawde-api-key: $LAWDE_API_KEY" \
  -d '{
    "error_class": "TypeError",
    "error_message": "Cannot read property of null",
    "stack_trace": "TypeError: Cannot read property of null\n    at handler (src/api/route.ts:42:11)",
    "file_path": "src/api/route.ts",
    "line_number": 42,
    "environment": "production"
  }'
```

A stored error answers HTTP 200 with `"success": true` and a `cluster_id`. Full contract: [HTTP / cURL](https://www.lawde.net/docs/sdk/http).

## 4. See your first event

Throw an error in a real route of your running app, then open [Overview](https://www.lawde.net/dashboard) or Issues. Identical crashes group into one issue, and look-alikes join it when their similarity is at least 0.85. Secrets are scrubbed before the event is stored.

Nothing showing? The agent does not print LAWDE’s reply, so send one test error with the cURL command above (or run `npx @lawdeshield/cli init` again) to see the exact message, then look it up in [Troubleshooting](https://www.lawde.net/docs/troubleshooting).

## 5. Connect GitHub

Open [Profile → Connected Services](https://www.lawde.net/profile?tab=services), install the LAWDE AI GitHub App and pick the repository for this app. Access is read-only and limited to that installation.

For one diagnosis, Beacon reads a short window of source around the crash line at the crashing release. That source is used for that diagnosis and dropped; LAWDE does not keep a copy. Paths listed in a root `.lawdeignore` are never fetched or sent to AI: see [.lawdeignore](https://www.lawde.net/docs/lawdeignore).

## 6. Run your first diagnosis

Open the issue and click Diagnose. Athena explains what broke, why, and where to fix it. It runs only when you ask, when your app has sent a real event, when GitHub is connected, and when your daily AI quota has room.

Aegis scores each diagnosis on evidence it checks itself, such as your code in the crash frame and the error on the crash line. A suggested patch is shown only when the diagnosis score is at least 0.70 and the patch applies to your source. Below that you see the diagnosis and its weak points, not a patch. A suggested patch is generated, not verified: review it like any other change.

After a fix ships, Fix verification (beta) can follow it from the pull request to the release and report Resolved, Recurred or not enough evidence yet. See the [sample case](https://www.lawde.net/sample-case) (sample data).

## Frequently asked questions

### Does npx @lawdeshield/cli init change files without asking?

No. It shows each change as a diff and asks before writing it. --dry-run writes, installs and sends nothing; --yes accepts every change for scripts and CI.

### What does the ✓ after the test error mean?

LAWDE’s response confirmed it stored the test error. It checks your key and app; your own errors are reported once your app runs with the new code.

### Which frameworks does Quick setup support?

Next.js, Express, Node servers with an entry file, and Medusa v2. For anything else, send errors to the HTTP ingest API.

### Does LAWDE store my source code?

No. Source read from GitHub is used for one diagnosis and then dropped. LAWDE keeps the diagnosis result, not your code.
