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

# Magic Links

> Let your users verify their phone number by opening a link on your own domain instead of typing the code.

With magic links, the verification SMS carries a link on a subdomain you own, for example
`https://verify.example.com/V1StGXR8_Z5j`, instead of a code. The user opens it and is redirected to your
application.

> [!NOTE]
>
> Magic links are available on request. To enable them, [contact us](mailto:support@prelude.so) with the
> subdomain you want to use, the default URL your users land on after opening a link, and the domains you want
> to redirect to per verification, if any.

# How it works

1. You create a verification with a magic link template.
2. Prelude sends the SMS with the link.
3. The user opens the link. Prelude checks the verification, exactly as a correct code sent to
   [`POST /v2/verification/check`](https://docs.prelude.so/verify/v2/api-reference/check-a-code) would.
4. Prelude redirects the user to your redirect URL. It keeps the URL's own query parameters as they are,
   and adds these:

| Parameter | Description |
| - | - |
| `status` | `success`, `expired` (the verification expired or does not exist) or `invalid`. |
| `verification_id` | The ID of the verification, as returned on creation (`vrf_…`). Not present when `invalid`. |
| `prelude_token` | A signed JWT with the same outcome. Present only when you have a webhook signing key. |

Use `status` to choose what to show the user. Sign the user in only from `prelude_token`.

`invalid` also covers an account that cannot check verifications at that moment, for example when its
balance is too low, as for `POST /v2/verification/check`.

Link previews and security scanners (in messaging apps or mail filters) open links before the user does.
Prelude detects common link previews and scanners and redirects them to your redirect URL without checking
the verification and without query parameters. This detection is best effort: treat a `success` as proof that
the link was opened, not that a person opened it.

# Verify the redirect

The redirect goes through the user's browser, so `status` and `verification_id` can be changed.
`prelude_token` is a JWT signed with your
[webhook signing key](https://docs.prelude.so/verify/v2/documentation/webhook.md#webhook-signature), so your backend can trust it once
it is verified.

The token is signed with `PS256` (RSASSA-PSS with SHA-256). Its claims are:

| Claim | Description |
| - | - |
| `iss` | Always `prelude`. |
| `aud` | Your magic link domain, for example `verify.example.com`. |
| `sub` | The verification ID (`vrf_…`). Absent when `status` is `invalid`. |
| `status` | `success`, `expired` or `invalid`. |
| `iat` | The time of the redirect, in Unix seconds. |
| `exp` | 5 minutes after `iat`. |
| `jti` | A unique ID of the token. |

Sign the user in only when:

1. the token is valid for your public key, the `PS256` algorithm, `iss`, `aud` and `exp`. Use a JWT library:
   it checks all of them;
2. `status` in the token is `success`;
3. `sub` is the verification ID you received when you created the verification for this user session;
4. you have not accepted this `jti` or this verification ID before.

> [!WARNING]
>
> Without a webhook signing key, the redirect has no `prelude_token` and you cannot trust it. Generate a key in the
> [Prelude dashboard](https://app.prelude.so/), in **Verify API->Configure->Webhooks**, before you enable
> magic links.

```js Node.js theme={null}
// npm install jose
const { importSPKI, jwtVerify } = require("jose");

async function verifyMagicLinkRedirect(token, expectedVerificationId, publicKeyPem) {
  const key = await importSPKI(publicKeyPem, "PS256");
  const { payload } = await jwtVerify(token, key, {
    algorithms: ["PS256"],
    issuer: "prelude",
    audience: "verify.example.com",
  });

  // Also store payload.jti and refuse a token you have already accepted.
  return payload.status === "success" && payload.sub === expectedVerificationId;
}
```

```python Python theme={null}
# pip install "pyjwt[crypto]"
import jwt


def verify_magic_link_redirect(token: str, expected_verification_id: str, public_key_pem: str) -> bool:
    claims = jwt.decode(
        token,
        public_key_pem,
        algorithms=["PS256"],
        issuer="prelude",
        audience="verify.example.com",
        options={"require": ["exp", "iat", "jti", "sub"]},
    )

    # Also store claims["jti"] and refuse a token you have already accepted.
    return claims["status"] == "success" and claims["sub"] == expected_verification_id
```

```go Go theme={null}
// go get github.com/golang-jwt/jwt/v5
import (
	"crypto/rsa"
	"errors"

	"github.com/golang-jwt/jwt/v5"
)

type magicLinkClaims struct {
	Status string `json:"status"`
	jwt.RegisteredClaims
}

func verifyMagicLinkRedirect(token, expectedVerificationID string, pub *rsa.PublicKey) error {
	var claims magicLinkClaims
	_, err := jwt.ParseWithClaims(token, &claims, func(*jwt.Token) (any, error) { return pub, nil },
		jwt.WithValidMethods([]string{"PS256"}),
		jwt.WithIssuer("prelude"),
		jwt.WithAudience("verify.example.com"),
		jwt.WithExpirationRequired(),
	)
	if err != nil {
		return err
	}

	// Also store claims.ID (jti) and refuse a token you have already accepted.
	if claims.Status != "success" || claims.Subject != expectedVerificationID {
		return errors.New("not a success for this verification")
	}

	return nil
}
```

# Set up your domain

After we register your subdomain, we send you the DNS records to publish:

* a `CNAME` record that points your subdomain to Prelude;
* a `CNAME` record under `_acme-challenge.<your subdomain>` that lets Prelude issue the TLS certificate;
* a `TXT` record under `_cf-custom-hostname.<your subdomain>` that proves you own the subdomain. It is optional
  once the first `CNAME` record is published, and it lets you set up the domain before you point the subdomain to
  Prelude.

The domain becomes active once the records are published and the certificate is issued, usually within a
few minutes. Until then, a request with your magic link template returns a 400 error with the
`magic_link_not_configured` code.

# Create a verification with a magic link

In the [Prelude dashboard](https://app.prelude.so/), in **Verify API->Configure**, create a template with the
**Magic Link** type. Its message carries the link and no code, in the language of the user. Pass its ID as
`template_id`:

```bash theme={null}
curl https://api.prelude.dev/v2/verification \
  -H "Authorization: Bearer $API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "target": { "type": "phone_number", "value": "+30123456789" },
    "options": { "template_id": "template_01jd1xq0cffycayqtdkdbv4d61" }
  }'
```

The message looks like this:

```
Tap this link to verify your phone number: https://verify.example.com/V1StGXR8_Z5j
```

Your other templates keep sending a code, without a link.

A magic link verification is sent by SMS only: other channels, such as WhatsApp, cannot carry the link, so
Prelude does not fall back to them. Some countries and carriers filter SMS that contain a URL. Tell us the
countries you plan to send to, so we can check the routes before you start.

# Choose the redirect URL per verification

By default, the user lands on the redirect URL set up for your domain. To send this user somewhere else, for
example to a recovery page that carries your own token, set `redirect_url`:

```json theme={null}
"options": {
  "template_id": "template_01jd1xq0cffycayqtdkdbv4d61",
  "magic_link": { "redirect_url": "https://example.com/password/recovery/3f9a2c" }
}
```

`magic_link` is accepted only with a magic link template. With any other template, the request returns a 400
error with the `magic_link_not_configured` code.

The URL must use `https`, and its domain must be one of your **allowed redirect domains**, which we set up
with you. The match is exact: allowing `example.com` does not allow `www.example.com`, which must be allowed on
its own. Its query must not use `status`, `verification_id` or `prelude_token`, which Prelude adds. Any other
URL returns a 400 error with the `invalid_magic_link_redirect_url` code, and nothing is sent. This keeps a
stolen API key from sending your users to another site.

A request with a different `redirect_url` on the same phone number starts a new verification, so the new SMS
carries a link to the new URL. Link previews and security scanners are always redirected to your default
redirect URL, never to the URL of the verification.

The link is valid as long as the verification: once it expires, the user lands on your redirect URL with
`status=expired`, even if the verification succeeded. Opening the link again after a success and before the
expiry redirects with `status=success` and does not create a second check.


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