> ## Documentation Index
> Fetch the complete documentation index at: https://docs.air3.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart: Issuing your first credential

> Run the AIR issuer service, register it with AIR, and issue your first SD-JWT credential to a logged-in user with AIR Kit.

This guide implements on-demand issuance with the user present. Your app calls
`issueCredential()` to open the AIR flow. The SDK handles login, credential
discovery, and user confirmation; AIR forwards issuance to your backend, which
authorizes the request, retrieves the data, creates and signs the credential,
encrypts it, and stores it in dStorage.

New issuance programs use the `SD_JWT_VC` proof type. This setup is self-serve
in both sandbox and production. To issue Iden3 (`BJJ_SIG_2021`) credentials
instead, see [Issue Iden3 credentials](https://docs.air3.com/products/identity/iden3/issuing).

> [!NOTE]
>
> This guide covers user-initiated SDK issuance through a self-hosted issuer
> backend. To issue from a backend event with no user session, see
> [Direct issuance](https://docs.air3.com/products/identity/issuing-credentials#direct-issuance).

## Before you start

You need:

* A supported Node.js version
* An issuer backend implementing `available-vc` and `issue-vc`, reachable by AIR
  over HTTPS. You can host it or use an HTTPS tunnel during development.
* An AIR Developer Dashboard account and Partner ID
* A server endpoint that signs Partner JWTs, and a public HTTPS JWKS endpoint (you set both up in Step 6)
* A web app served over HTTPS, with its origin whitelisted under **Account → Domains**

**A database is optional in sandbox.**
For development and testing, credential data can come from an existing API or service, or you can use static sample data.
For production, however, if you need to support features such as **credential revocation, issuance history, and token status lists,**
especially at scale with many users, you will need to persist the relevant data in your own database.

Regardless of whether you use a database, encrypted credentials are stored in dStorage.

The backend and JWKS endpoint can share a host. See [Issuer backend hosting](https://docs.air3.com/products/identity/backend-hosting.md).

> [!WARNING]
>
> Choose a stable public origin for the issuer service before you issue. The issuer DID is `<host of ISSUER_ORIGIN>`, so changing the host later changes your issuer identity.

## What you will build

By the end of this guide, you will have:

* A public issuer backend with `POST /available-vc`, `POST /issue-vc`, a
  revocation-status endpoint, and a `did:web` document
* An SD-JWT credential-type registration and issuance program in the Dashboard
* A backend claims implementation, registered with the reference issuer service
* A public JWKS endpoint and a server-only Partner JWT endpoint
* A web flow that logs in with AIR Kit and calls `issueCredential`

> [card] [AIR issuer service (SD-JWT)](https://github.com/MocaNetwork/air-issuer-service/tree/main_sd-jwt-vc)
>
> Issuer endpoints, schema logic, SD-JWT signing, encryption, revocation, and dStorage integration.

## How SDK issuance works

1. Your app starts `issueCredential()` with the issuer and issuance program.
2. The user logs in to AIR if needed.
3. The SDK requests available credentials through AIR. AIR calls the registered
   issuer backend's `POST /available-vc` and returns encrypted previews.
4. The SDK decrypts and displays the previews. The user selects a credential and
   confirms issuance.
5. The SDK requests issuance through AIR, which calls the issuer's `POST /issue-vc`
   with the resolved holder identity, encryption key, holder signing key, and schema.
6. The issuer authorizes the request, loads authoritative claims, creates and
   signs the SD-JWT VC, encrypts it, and stores it in dStorage.
7. The SDK reports completion to your app. If the user declines, issuance stops.

The browser does not need the issuer API key or a separate request to fetch claims.
See [Architecture and data flow](https://docs.air3.com/technicals/architecture.md) for the sequence diagram.

The issuance program ID is an AIR Kit and Dashboard identifier. Your issuer
backend works with a `schemaId`, not the program ID.

## Step 1: Generate partner secrets

Clone the SD-JWT branch of the [AIR issuer service](https://github.com/MocaNetwork/air-issuer-service/tree/main_sd-jwt-vc),
or your fork of it, then install its dependencies:

```bash theme={null}
git clone -b main_sd-jwt-vc https://github.com/MocaNetwork/air-issuer-service.git
cd air-issuer-service
npm i
```

Check the branch README and `.env.example` when you upgrade.

Generate separate API keys for AIR-to-issuer calls and admin calls:

```bash theme={null}
echo "API_KEY=$(openssl rand -hex 32)"
echo "ADMIN_API_KEY=$(openssl rand -hex 32)"
```

Generate an RSA key pair for Partner JWT signing:

```bash theme={null}
openssl genpkey \
  -algorithm RSA \
  -pkeyopt rsa_keygen_bits:2048 \
  -out partner-private.pem

openssl pkey \
  -in partner-private.pem \
  -pubout \
  -out partner-public.pem
```

You will use the same key pair in three places:

* The issuer backend signs the SD-JWT credentials and its requests to dStorage
  with the private key.
* Your web server signs short-lived AIR Kit Partner JWTs with the private key.
* The public key is published through your JWKS and the issuer's `did:web`
  document, so AIR and verifiers can check both.

Never expose the private key through a `NEXT_PUBLIC_*` environment variable.

## Step 2: Configure and start the issuer backend

Create the issuer backend environment file:

```bash theme={null}
NODE_ENV=sandbox

# Optional in sandbox; required for revocation, history, and the status list at scale
# DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/issuer-backend

# Public origin of this issuer service, without a trailing slash.
# The issuer DID is did:web:<host of this origin>.
ISSUER_ORIGIN=https://issuer.example.com

# Partner identity and signing
PARTNER_ID=<dashboard-partner-id>
PARTNER_PRIVATE_KEY_KID=<kid-in-your-jwks>
PARTNER_PRIVATE_KEY_ALG=RS256
PARTNER_PRIVATE_KEY_DER=<pkcs8-private-key-body-without-pem-markers>
PARTNER_JWKS=<public-JWKS-JSON-containing-the-matching-kid>

# AIR-to-issuer and operator authentication
API_KEY=<generated-api-key>
ADMIN_API_KEY=<generated-admin-api-key>

# Optional
# AIR_API_ORIGIN and MOCA_CHAIN_API_ORIGIN default per NODE_ENV
# SD_JWT_TSL_PARTITION_SIZE=80000   # enables the token status list; see Revoke credentials
PORT=3000
```

`PARTNER_PRIVATE_KEY_DER` is the base64 body between the `BEGIN PRIVATE KEY`
and `END PRIVATE KEY` lines in `partner-private.pem`. It must be PKCS#8.

`PARTNER_JWKS` contains public keys only, matching your Partner JWT signing key
and `kid`. Generate and publish the document using [JWKS endpoint setup](https://docs.air3.com/get-started/authentication/jwks-endpoint.md).
The service serves these keys in its `did:web` document and issuer metadata.

If you set `DATABASE_URL` (this issuer service uses PostgreSQL), apply migrations before the first start:

```bash theme={null}
npx mikro-orm migration:up
```

Start the service:

```bash theme={null}
npm run start:dev
```

Once `ISSUER_ORIGIN` is reachable over HTTPS, confirm the public identity routes:

```bash theme={null}
curl https://issuer.example.com/.well-known/did.json
curl https://issuer.example.com/.well-known/jwt-vc-issuer
```

`did.json` returns the issuer DID (`did:web:issuer.example.com`) with your
public keys as verification methods. Credentials are signed with header
`kid` set to `<issuer DID>#<PARTNER_PRIVATE_KEY_KID>`.

> [!NOTE]
>
> The credential `iss` is the `did:web` DID, while `/.well-known/jwt-vc-issuer`
> identifies the HTTPS origin. AIR verification resolves the DID document.
> Some external verifiers expect these identifiers to match exactly; test with
> the verifier you plan to support.

## Step 3: Register the issuer with AIR

Expose the issuer backend over public HTTPS. Register the issuer under
**Dashboard → Issuer → Settings** in the sandbox or production Dashboard, then
configure its endpoint URLs:

| Item | Value |
| - | - |
| Issuer DID | `did:web:<host of ISSUER_ORIGIN>` |
| Signature type | `SD_JWT_VC` |
| API key | The backend `API_KEY` |
| Partner ID | Your Dashboard Partner ID |
| Available credentials URL (`availableVcApiUrl`) | `https://issuer.example.com/available-vc` |
| Issuance URL (`issueVcApiUrl`) | `https://issuer.example.com/issue-vc` |
| Revocation status URL (`revocationStatusApiUrl`) | Your issuer's `GET /revocation-status/:nonce` route |

After registration:

1. Confirm the Issuer DID in the Dashboard matches the `id` in your
   `/.well-known/did.json`.
2. Confirm AIR can reach both registered issuer endpoints over HTTPS.
3. Keep `API_KEY` identical to the value you registered with AIR.

AIR calls these issuer endpoints with `x-api-key`. Keep the key server-side;
your browser calls AIR Kit with a short-lived Partner JWT. A missing or incorrect
issuer API key causes the backend to return `403`.

If you enable CORS on the issuer or a proxy in front of it, allow `*.air3.com`.

## Step 4: Register the credential type and create an issuance program

After registering your issuer:

1. Open the Dashboard for your target environment. For this guide, use the
   [Sandbox Developer Dashboard](https://developers.sandbox.air3.com).
2. Go to **Issuer → Schemas**.
3. Register a credential type for this example, such as
   `urn:example:credential:historical-amount:v1`.
4. Optionally provide Type Metadata JSON describing the `historical_amount`
   claim.
5. Publish the record and save its schema ID and `vct`.
6. Go to **Issuer → Programs** and create an issuance program using that schema
   record.
7. Use the `SD_JWT_VC` proof type and save the issuance program ID.

This step registers the credential type with AIR. You will define the
`historical_amount` claim and its selective-disclosure behavior in your backend
in Step 5.

Use the same `vct` in the Dashboard registration and the credential your backend
issues. The reference implementation may fall back to `schemaId` when no
explicit `vct` is configured; this quickstart sets it explicitly to avoid
ambiguity. See
[Registering credential types and creating schemas](https://docs.air3.com/products/identity/schema-creation.md).

## Step 5: Implement the credential data

In the reference issuer service, a backend schema class maps the Dashboard
schema ID to your claims-generation logic, credential-type identifier, expiry,
and disclosure configuration. This class is separate from the Dashboard schema
record and optional Type Metadata.

```ts src/issuer/sd-jwt-vc-schemas/schema_<SCHEMA_ID>.ts theme={null}
import { DisclosureFrame } from "@sd-jwt/core";
import { BaseSchema } from "./base-schema";

type Claim = {
  historical_amount: string;
};

class Schema_<SCHEMA_ID> extends BaseSchema<Claim> {
  public readonly schemaId = "<SCHEMA_ID>";
  public readonly vct =
    "urn:example:credential:historical-amount:v1";
  public readonly ["vct#integrity"] = undefined;
  public readonly disclosureFrame: DisclosureFrame<Claim> = {
    _sd: ["historical_amount"], // claims the holder can disclose selectively
  };
  public readonly expirySec = 30 * 24 * 60 * 60;

  async generateCredentialData(userId: string) {
    // Load attributes from your database or API using userId
    return {
      credentialSubject: {
        historical_amount: "1000",
      },
      expiration: Math.floor(Date.now() / 1000) + this.expirySec,
    };
  }
}

export default new Schema_<SCHEMA_ID>();
```

Register the instance so `/available-vc` and `/issue-vc` can resolve its
`schemaId`:

```ts src/issuer/sd-jwt-vc-schemas/index.ts theme={null}
import { BaseSchema } from "./base-schema";
import HistoricalAmountSchema from "./schema_<SCHEMA_ID>";

const schemas: BaseSchema<any>[] = [HistoricalAmountSchema];

export default schemas;
```

Follow these rules:

* Validate claim names, types, and values in your backend. If you publish Type
  Metadata, keep it consistent with the claims you issue. Type Metadata is not
  automatic runtime validation.
* Do not return reserved claims from `generateCredentialData`: `id`, `nonce`,
  `vct`, `sub`, `exp`, `cnf`, `iss`, `iat`, or `status`. The service sets them.
* `expirySec` sets the credential's `exp`. The `expiration` you return is only
  used for the preview.
* List a claim in `disclosureFrame._sd` only if verifiers may request it on
  its own. Claims outside `_sd` are always visible in a presentation.
* Keep the backend authoritative. Do not sign claim values supplied by the
  browser without validating them against your own data.
* When you replace the static example with a database or API lookup, use the
  partner user ID at the issuer boundary for eligibility and data
  retrieval.

### Issuer endpoint contract

AIR calls both issuer endpoints during on-demand issuance: `POST /available-vc`
provides encrypted previews, and `POST /issue-vc` performs issuance after the user
confirms. The issuer validates eligibility using the AIR-resolved partner user
identifier and retrieves claims from its own data source.

> [accordion] Issuer endpoint requests and responses
>
> `POST /available-vc` accepts the holder identity and optional filters:
>
> ```json theme={null}
> {
>   "holderDID": "did:air:...",
>   "pubKey": "0x...",
>   "userId": "<partner-primary-id>",
>   "schemaId": "<optional-schema-id>",
>   "proofType": "SD_JWT_VC"
> }
> ```
>
> It returns encrypted previews:
>
> ```json theme={null}
> {
>   "data": [
>     {
>       "holderDID": "did:air:...",
>       "schemaId": "<SCHEMA_ID>",
>       "credentialSubject": {
>         "encryptedData": "...",
>         "iv": "...",
>         "authTag": "...",
>         "dataEncPublicKey": "..."
>       },
>       "proofType": "SD_JWT_VC"
>     }
>   ]
> }
> ```
>
> `POST /issue-vc` accepts the selected schema and the holder's signing key:
>
> ```json theme={null}
> {
>   "holderDID": "did:air:...",
>   "pubKey": "0x...",
>   "userId": "<partner-primary-id>",
>   "schemaId": "<SCHEMA_ID>",
>   "signingKey": { "jwk": { "kty": "EC", "crv": "P-256", "x": "...", "y": "..." } },
>   "proofType": "SD_JWT_VC"
> }
> ```
>
> On success, the issuer backend:
>
> 1. Generates the credential data.
> 2. Sets `sub` to `holderDID` and `cnf` to the holder's signing public key
>    from `signingKey`, which AIR always sends. This binds the credential to the holder.
> 3. Signs the SD-JWT VC with your partner key under the `did:web` issuer DID.
> 4. Encrypts the credential to `pubKey`.
> 5. Persists the issuance record when database persistence is enabled.
> 6. Uploads the encrypted credential to dStorage.
> 7. Returns HTTP `201` with an empty response body.
>
> AIR sends `x-api-key: <API_KEY>` to both endpoints. This issuer HTTP response is
> distinct from the SDK result returned to your app.

## Step 6: Install AIR Kit and set up Partner authentication

Install AIR Kit in your web application:

```bash theme={null}
npm i @mocanetwork/airkit
```

Add the browser-safe and server-only values to your web environment:

```bash theme={null}
# Browser-safe
NEXT_PUBLIC_PARTNER_ID=<dashboard-partner-id>
NEXT_PUBLIC_ISSUER_DID=<issuer-did>
NEXT_PUBLIC_ISSUE_PROGRAM_ID=<dashboard-program-id>
NEXT_PUBLIC_BUILD_ENV=sandbox

# Server-only
PARTNER_PUBLIC_KEY=<public-key-body-without-pem-markers>
PARTNER_PRIVATE_KEY=<pkcs8-private-key-body-without-pem-markers>
SIGNING_ALGORITHM=RS256
```

### Set up the JWKS endpoint

Issuance fails until AIR can fetch your JWKS. Follow [JWKS endpoint](https://docs.air3.com/get-started/authentication/jwks-endpoint.md),
then check that the registered URL returns the `kid` your Partner JWT will use.

### Sign the Partner JWT

Implement the [Next.js Partner JWT
endpoint](https://docs.air3.com/get-started/authentication/sdk-auth.md#nextjs-partner-jwt-endpoint).
The endpoint must generate a short-lived token on the server with
`scope: "issue"` and a `kid` that appears in your registered JWKS.

## Step 7: Initialize AIR Kit and issue the credential

The frontend examples use Next.js. Create a singleton AIR service and a helper
for fetching the Partner JWT. Call these helpers from a browser event handler.

```ts lib/air.ts theme={null}
import { AirService, BUILD_ENV } from "@mocanetwork/airkit";

let servicePromise: Promise<AirService> | undefined;

export function getInitializedAirService(): Promise<AirService> {
  servicePromise ??= (async () => {
    const partnerId = process.env.NEXT_PUBLIC_PARTNER_ID;
    if (!partnerId) throw new Error("NEXT_PUBLIC_PARTNER_ID is required");

    const service = new AirService({ partnerId });
    await service.init({ buildEnv: BUILD_ENV.SANDBOX });
    return service;
  })().catch((error) => {
    servicePromise = undefined;
    throw error;
  });
  return servicePromise;
}

export async function fetchPartnerJwt(): Promise<string> {
  const response = await fetch("/api/partner-jwt", { method: "POST" });
  const body = (await response.json()) as {
    token?: string;
    error?: string;
  };

  if (!response.ok || !body.token) {
    throw new Error(
      body.error ?? `Partner JWT request failed (${response.status})`,
    );
  }

  return body.token;
}
```

Log in before starting issuance, then call `issueCredential`:

```ts theme={null}
import { fetchPartnerJwt, getInitializedAirService } from "@/lib/air";

export async function issueHistoricalAmountCredential() {
  const issuerDid = process.env.NEXT_PUBLIC_ISSUER_DID;
  const credentialId = process.env.NEXT_PUBLIC_ISSUE_PROGRAM_ID;
  if (!issuerDid || !credentialId) {
    throw new Error("Issuer DID and issuance program ID are required");
  }

  const air = await getInitializedAirService();

  if (!air.isLoggedIn) {
    await air.login();
  }

  const authToken = await fetchPartnerJwt();

  return air.issueCredential({
    authToken,
    issuerDid,
    credentialId,
    credentialSubject: {},
  });
}
```

Pass `{}` as `credentialSubject`: the AIR credential UI fetches encrypted
previews through AIR and the issuer backend supplies the authoritative claims.

The SDK promise resolves on success and rejects on failure. It does not return the VC or a dStorage path. Handle the SDK result separately from backend storage records.

## Step 8: Test end to end

Start the issuer backend and web app. For local testing, expose the web app through an [HTTPS tunnel](https://docs.air3.com/get-started/authentication/jwks-endpoint.md#local-development-https-tunnel), whitelist the tunnel domain under **Account → Domains**, and register the tunnel's JWKS URL. Then:

1. Open the web app at its HTTPS URL (the tunnel URL when testing locally).
2. Log in through AIR Kit.
3. Start credential issuance.
4. Confirm the AIR Credential UI shows the available credential.
5. Approve issuance.
6. Confirm the app receives a successful `issueCredential` result.

When database persistence is enabled, you can also check the backend issuance history:

```bash theme={null}
curl -s \
  -H "x-admin-api-key: <ADMIN_API_KEY>" \
  "https://issuer.example.com/admin/issuance-history?page=1&limit=25" \
  | jq .
```

Without database persistence, an empty history is not a failed issuance.
Confirm that the SDK completes successfully and that the holder's credential
can be discovered and used in the verification flow.

## Troubleshooting

### Issuer backend returns 403

The caller is not sending the expected `x-api-key`, or the value differs from the
backend `API_KEY`. Confirm the Partner ID, Issuer DID, and API key match what you
registered with AIR.

### AIR cannot validate the Partner JWT

Confirm the token contains `scope: "issue"` and has not expired. For JWKS and
`kid` checks, see [JWKS endpoint troubleshooting](https://docs.air3.com/get-started/authentication/jwks-endpoint.md#troubleshooting).

### No credential preview appears

Confirm AIR can call the registered `POST /available-vc` endpoint and that the
backend returns an encrypted preview for the logged-in holder. Check the
program's issuer DID, schema, proof type, and the user's eligibility.

### Credential type or backend configuration does not match

Confirm that:

* The issuance program uses `SD_JWT_VC`.
* The backend resolves the expected `schemaId`.
* The backend's explicit `vct` matches the registered credential type.
* Claims pass backend validation and contain no reserved claims such as `id`,
  `sub`, `vct`, or `cnf`.

### Issuer backend is unreachable

Check that the service is running, both issuer endpoint URLs are registered,
and your HTTPS domain or tunnel is reachable by AIR. If a development tunnel URL
changes, update `ISSUER_ORIGIN` and the registered URLs. This also changes the
issuer DID, so only do it before you issue credentials you want to keep.

## Next steps

* [Credential verification quickstart](https://docs.air3.com/get-started/quickstarts/verify-credentials.md)
* [Issuing credentials](https://docs.air3.com/products/identity/issuing-credentials)
* [Revoke credentials](https://docs.air3.com/products/identity/revocation.md)
* [Issuance API reference](https://docs.air3.com/api-reference/issuance-api.md)
* [Identity & Credential troubleshooting](https://docs.air3.com/help/identity-credential.md)
* [AIR Credential example](https://github.com/MocaNetwork/air-credential-example)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.