> For the complete documentation index, see [llms.txt](https://docs.jetadmin.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.jetadmin.io/api-reference/javascript-sdk/authentication.md).

# Configuration and authentication

### Configure a client

```typescript
import { Jet } from '@jet-admin/jet-sdk';

const jet = new Jet({
  project: 'YOUR_PROJECT',
  environment: 'prod',
  apiBaseUrl: 'https://data.jetadmin.io',
});
```

| Option        | Type                     | Default and behavior                                                                                  |
| ------------- | ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `project`     | `string`                 | No default. Supply your project identifier; the constructor does not validate it.                     |
| `environment` | `string`                 | `prod`                                                                                                |
| `apiBaseUrl`  | `string`                 | `https://data.jetadmin.io`; omit a trailing slash.                                                    |
| `draft`       | `boolean`                | Unset. When true, Axios requests include `draft=1`; agent prompts also include `draft` in their body. |
| `apiToken`    | `string`                 | Unset. Sent as `Authorization: Bearer <token>`.                                                       |
| `env`         | `Record<string, string>` | Optional environment-variable map.                                                                    |

Requests use `{apiBaseUrl}/projects/{project}/{environment}/` as their base URL.

#### Environment variables

Pass your environment map explicitly as `env`; the SDK does not read it automatically. It recognizes these pairs, preferring the `VITE_` value when present:

| Setting      | Environment keys                            |
| ------------ | ------------------------------------------- |
| Project      | `VITE_JET_PROJECT`, `JET_PROJECT`           |
| Environment  | `VITE_JET_ENVIRONMENT`, `JET_ENVIRONMENT`   |
| Draft        | `VITE_JET_DRAFT`, `JET_DRAFT`               |
| API base URL | `VITE_JET_API_BASE_URL`, `JET_API_BASE_URL` |

Explicit constructor options override values from `env`. Defined values override defaults. There is no environment-variable mapping for `apiToken`. Draft strings `false`, `0`, `no`, `off`, `null`, and `undefined` mean false, ignoring case and surrounding whitespace; an empty value is treated as unset.

### Sign users in

```typescript
import { Jet } from '@jet-admin/jet-sdk';

const jet = new Jet({ project: 'YOUR_PROJECT' });

async function signIn(email: string, password: string) {
  const { user } = await jet.auth.loginViaEmailPassword(email, password);
  return user;
}

async function currentUser() {
  const state = await jet.auth.isAuthenticated();
  return state.authenticated ? state.user : undefined;
}

async function signOut() {
  await jet.auth.logout();
}
```

Login returns `{ token: AuthState, user: UserInfo }`. The SDK stores tokens in the browser's `localStorage` under `jet_auth`, restores them when constructed, and sends access tokens with the `JWT` prefix. Before an authenticated request, it attempts refresh when either available token-expiry timestamp is less than 30 seconds away.

All clients on the same browser origin share the `jet_auth` storage key, including clients for different projects. A previously created client keeps its own in-memory state. Logging out clears that client's state and the storage entry; it does not revoke a token on the server or synchronize other clients and tabs.

`isAuthenticated()` returns `{ authenticated: false }` without an HTTP call when no headers are available. Request failures still reject the promise; catch them separately from a successful unauthenticated result.

### API tokens

`apiToken` takes the token value without a prefix. The SDK adds `Bearer` and prioritizes this option over user-session tokens. Use a token accepted by your project's SDK endpoints. A resource API documented with a raw Authorization token is not automatically compatible with this option.

Do not embed privileged API tokens in a public browser bundle. Use user authentication for browser examples. Server use requires resolving the runtime limitations below.

`logout()` does not clear a constructor's `apiToken`. To stop using it, discard the client and initialize a client without that option.

### Account methods

All methods below return promises. Availability and authorization depend on the project's authentication configuration.

| Method                                         | Arguments                                                                              | Resolved value                                                                                                                       |
| ---------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `registerViaEmailPassword(options)`            | Required `email`, `password`; optional `firstName`, `lastName`, `language`, `timezone` | Declared union `{ result: true, user }` or `{ result: false }`; successful implementation returns the first shape. Does not sign in. |
| `changePassword(newPassword, currentPassword)` | Pass a string or `undefined` for the second argument as required by your auth flow     | `{ result, newState }`; saves the returned tokens                                                                                    |
| `resetPassword(email)`                         | Email address                                                                          | `{ result }`                                                                                                                         |
| `resetPasswordComplete(code, newPassword)`     | Reset code and new password                                                            | `{ result, newState }`; saves the returned tokens                                                                                    |
| `changeEmail(newEmail, currentPassword)`       | New email and a string or `undefined` for the current password                         | `{ result, sentConfirmationTo }`                                                                                                     |
| `changeEmailComplete(code)`                    | Confirmation code                                                                      | `{ result, oldEmail, newEmail }`                                                                                                     |
| `getHeaders()`                                 | None                                                                                   | Authorization headers, or `undefined`                                                                                                |

`UserInfo` includes `uid`, `username`, `hasPassword`, and profile fields such as `email`, `firstName`, and `lastName`. `AuthState` contains access and refresh tokens and optional expiry dates. Avoid logging token objects.

### Service requests and server use

`Jet.fromServiceRequest(req)` reads `X-Jet-Project`, `X-Jet-Environment`, and `X-Jet-Service-Token` from `req.headers`. These three headers are required. Optional `X-Jet-API-Base-Url` and `X-Jet-Draft` are forwarded to the constructor. `jet.auth.loginViaServiceRequest(req)` only loads the service token into an existing client. Service tokens use the `JWT` prefix.

These methods still rely on `localStorage`. A request-scoped authentication/storage implementation is needed before using this version in a multi-user server. The SDK does not supply one. Also, `X-Jet-Draft` is not parsed as a boolean here: a string such as `"false"` is truthy. Only accept these configuration headers from a trusted service boundary, especially the API base URL that determines where credentials are sent.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.jetadmin.io/api-reference/javascript-sdk/authentication.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
