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

# API Link User Token Authentication

> Auto-sign authenticated users into Nudj using JWT tokens

This guide explains how to authenticate users directly into Nudj using JWT tokens that encode user metadata. Use this when your users are already authenticated in your system and you want to pass them into Nudj seamlessly.

<Info>
  **Use this method if**: Users are already logged into your platform and you want to continue their session in Nudj without showing a login screen.

  **If users arrive at Nudj directly to log in**, use [OAuth Integration Setup](/developer/oauth-authentication) instead.
</Info>

## Quick Start

1. Get your `clientId` and `clientSecret` from Nudj API Configuration
2. Generate a signed JWT containing user details using your `clientSecret`
3. Build the auto-login URL with the token and `clientId`
4. Redirect the user to that URL
5. They land in Nudj fully signed in

## When to Use This Method

Use API Link if:

* Users are already authenticated in your platform
* You want to pass them into Nudj without showing a login screen
* You're embedding Nudj in your app or redirecting from your dashboard
* You want the fastest, most seamless user experience

**Don't use this if** users arrive at Nudj directly without being authenticated—in that case, use [OAuth Integration Setup](/developer/oauth-authentication).

## Retrieve Your Credentials

1. Log into your Nudj admin panel
2. Navigate to **Organisation Settings → API Configuration**
3. Copy these values:
   * **Client ID**
   * **Client Secret**

You'll need these to sign tokens and identify your organization.

## Generate the User Token

The user token is a JWT (JSON Web Token) signed with your `clientSecret`. It must contain these properties:

```javascript theme={null}
import { sign } from "jsonwebtoken";

const userData = {
  userId: "abc123",              // ✅ REQUIRED: Unique ID for this user
  email: "user@example.com",     // ⚠️ Optional but recommended
  locale: "en",                  // ✅ REQUIRED: Language code (e.g., "en", "fr", "es")
};

function signUserToken(input) {
  const clientSecret = "YOUR_CLIENT_SECRET"; // From API Configuration
  return sign(input, clientSecret, { expiresIn: "1h" });
}

const userToken = signUserToken(userData);
console.log("Generated token:", userToken);
```

### Token Properties

| Property             | Required?   | Description                                                                                                                                  |
| -------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`             | ✅ Yes       | Unique identifier for the user. Stored as `externalId` in Nudj.                                                                              |
| `email`              | ⚠️ Optional | User's email address. Must be unique per user. If omitted, Nudj generates a placeholder email and the user can only log in via direct links. |
| `locale`             | ✅ Yes       | Language/region code (e.g., "en", "fr", "es"). Defaults to "en" if not provided.                                                             |
| `username`           | ⚠️ Optional | Display name shown in Nudj UI. Defaults to "anonymous" until updated.                                                                        |
| `anonymousAccountId` | ⚠️ Optional | Provided by Nudj to merge an anonymous session with the user's account.                                                                      |

## Auto-Sign the User Into Nudj

Once you have the `userToken`, build the login URL:

```javascript theme={null}
const domain = "loyalty.mycompany.com";     // Your Nudj domain
const clientId = "YOUR_CLIENT_ID";          // From API Configuration
const userToken = "YOUR_GENERATED_TOKEN";   // From previous step

const linkUrl = `https://${domain}/api/link?userToken=${userToken}&clientId=${clientId}`;

// Redirect the user to this URL
window.location.href = linkUrl;
```

The user will be redirected to Nudj and automatically logged in.

## How It Works

### Account Identification

Each user is identified by their `userId`. If a user with that `userId` already exists, their record is updated. If not, a new account is created.

### Account Creation

When a new user arrives with an `API Link` token:

1. Nudj checks if a user with that `userId` already exists
2. If not, creates a new account with the provided details
3. The user is logged in immediately

### Account Updates

If a user logs in again with updated information (different email, locale, username):

* Nudj updates the existing user record with the new values
* The user's existing data and history are preserved

### Email Handling

* **If `email` is provided**: Nudj uses it to identify and email the user
* **If `email` is omitted**: Nudj generates a placeholder email; the user can only log in via direct links (no magic link or self-serve login)

## Example Integration Flow

Here's a complete example of how API Link authentication flows:

<Steps>
  <Step title="User logs into your platform">
    Your user authenticates with your system (however you handle that)
  </Step>

  <Step title="Backend generates token">
    Your backend code signs a JWT with the user's details using your `clientSecret`
  </Step>

  <Step title="Frontend builds the link">
    Your frontend creates the login URL with the token and `clientId`
  </Step>

  <Step title="User is redirected">
    Your frontend redirects the user to the Nudj login URL
  </Step>

  <Step title="User lands in Nudj authenticated">
    Nudj verifies the token, creates/updates the user, and logs them in—no login screen shown
  </Step>
</Steps>

## Code Example: Node.js Backend

```javascript theme={null}
const express = require("express");
const { sign } = require("jsonwebtoken");
const app = express();

// These come from your Nudj API Configuration
const NUDJ_CLIENT_ID = "your_client_id";
const NUDJ_CLIENT_SECRET = "your_client_secret";
const NUDJ_DOMAIN = "loyalty.mycompany.com";

// Endpoint that generates the login link
app.get("/nudj-login-link", (req, res) => {
  // Get the authenticated user from your system
  const user = req.user; // Assuming you have authentication middleware

  // Create the token payload
  const tokenPayload = {
    userId: user.id,
    email: user.email,
    locale: user.preferredLanguage || "en",
    username: user.displayName,
  };

  // Sign the token
  const userToken = sign(tokenPayload, NUDJ_CLIENT_SECRET, {
    expiresIn: "1h",
  });

  // Build the Nudj login URL
  const loginUrl = `https://${NUDJ_DOMAIN}/api/link?userToken=${userToken}&clientId=${NUDJ_CLIENT_ID}`;

  // Return the URL to your frontend
  res.json({ loginUrl });
});

app.listen(3000, () => console.log("Server running"));
```

## Code Example: React Frontend

```jsx theme={null}
import { useEffect, useState } from "react";

export function NudjLoginButton() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleLogin = async () => {
    setLoading(true);
    setError(null);

    try {
      // Call your backend to get the login URL
      const response = await fetch("/nudj-login-link");
      const { loginUrl } = await response.json();

      // Redirect to Nudj
      window.location.href = loginUrl;
    } catch (err) {
      setError("Failed to generate login link");
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={handleLogin} disabled={loading}>
        {loading ? "Connecting..." : "Go to Loyalty Program"}
      </button>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </div>
  );
}
```

## Security Considerations

<CardGroup cols={1}>
  <Card title="Protect Your Client Secret" icon="lock">
    Your `clientSecret` is sensitive. Only use it on your backend, never in frontend code or client-side JavaScript.
  </Card>

  <Card title="Use HTTPS" icon="shield-check">
    Always use HTTPS for token generation and transmission. HTTP will expose tokens.
  </Card>

  <Card title="Token Expiration" icon="clock">
    Set token expiration to a reasonable value (1 hour is typical). Shorter is more secure; longer is more convenient.
  </Card>

  <Card title="Validate User Input" icon="check">
    Sanitize user data before putting it in the token. Never include sensitive information like passwords or API keys.
  </Card>
</CardGroup>

## Troubleshooting

<Accordion title="User lands on a login page instead of being signed in" icon="question">
  This usually means the token is invalid or the `clientId` is wrong. Verify:

  * The token was signed with your correct `clientSecret`
  * The `clientId` matches your API Configuration
  * The token hasn't expired
  * The token is being passed in the URL correctly
</Accordion>

<Accordion title="'Invalid token' error" icon="alert-circle">
  The token signature is invalid. This means either:

  * You're using the wrong `clientSecret` to sign the token
  * The token was tampered with or corrupted
  * You're using a different algorithm than expected (use `HS256`, the default for `jsonwebtoken`)

  Verify your `clientSecret` is correct and hasn't been rotated.
</Accordion>

<Accordion title="User created but missing data" icon="user">
  Some user properties are optional. If you didn't include `email`, Nudj generates a placeholder. If you didn't include `username`, it defaults to "anonymous".

  Include all desired properties in the token payload, and they'll be stored.
</Accordion>

<Accordion title="Same user landing with different emails" icon="question">
  Each `userId` should map to exactly one `email`. If you send the same `userId` with different emails, Nudj updates the user's email. This might cause issues if you expect a 1:1 mapping.

  Ensure your `userId` and `email` are always consistent for the same user.
</Accordion>

## Next Steps

1. Get your API credentials from Nudj API Configuration
2. Implement token generation in your backend
3. Build the login URL on your frontend
4. Test with a real user
5. Monitor for errors in your logs

Need help? Contact Nudj support.
