Skip to content

Commit 8dd1fc1

Browse files
authored
docs: document auth.withAuth scoped authentication helper (#3436)
1 parent 8aa1e55 commit 8dd1fc1

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

docs/management/authentication.mdx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,31 @@ await envvars.update("proj_1234", "preview", "DATABASE_URL", {
158158
value: "your_preview_database_url",
159159
});
160160
```
161+
162+
### Scoped authentication with `auth.withAuth`
163+
164+
`auth.withAuth` runs a callback with a temporary API client configuration, then restores the previous configuration when the callback resolves or rejects. It's useful when a single process needs to make calls across multiple Trigger.dev projects or environments without mutating the global config manually.
165+
166+
```ts
167+
import { auth, runs } from "@trigger.dev/sdk";
168+
169+
const projectBRuns = await auth.withAuth(
170+
{ accessToken: process.env.TRIGGER_SECRET_KEY_PROJECT_B },
171+
async () => {
172+
return runs.list({ limit: 10 });
173+
},
174+
);
175+
```
176+
177+
Any SDK call inside the callback uses the overridden token. Calls outside the callback continue to use whatever was set by `configure` (or picked up from `TRIGGER_SECRET_KEY`).
178+
179+
<Warning>
180+
Avoid `auth.withAuth` as a per-request authentication strategy on long-running servers. Use it
181+
only for sequential, non-overlapping scopes.
182+
</Warning>
183+
184+
#### How scoping actually works
185+
186+
Despite looking block-scoped, `auth.withAuth` stores the overridden configuration in a process-wide global (not [AsyncLocalStorage](https://nodejs.org/api/async_context.html)). It saves the previous config, installs the new one globally, runs the callback, and restores the previous config in a `finally`. This means sequential, non-overlapping usage is safe, but concurrent usage is not — if two `auth.withAuth` calls overlap (for example inside `Promise.all` with different tokens, or across concurrent request handlers on a long-running server) both will share whichever configuration was installed most recently, and SDK calls in one scope can silently use the other scope's token.
187+
188+
A fix using async context isolation is tracked in [issue #3298](https://github.com/triggerdotdev/trigger.dev/issues/3298).

0 commit comments

Comments
 (0)