Skip to main content
This guide explains how to authenticate users directly into the Nudj Platform using JWT tokens that encode user metadata. This method is suitable for scenarios where users are already authenticated in your platform and you want to pass them into Nudj seamlessly.

Quick Start ✅

1

Verify Prerequisites

Ensure users are already authenticated in your platform and you want to pass them into Nudj without showing a login screen.
2

Get Credentials

Retrieve your credentials from Developer Settings:
  • Client ID
  • Client Secret
  • API Token (for alternative method)
3

Generate User Token

Generate a signed JWT containing the user’s details (userId, email, locale, etc.) using your clientSecret.
4

Build Auto-Login URL

Create the authentication URL:
https://${yourDomain}/api/link?userToken=${userToken}&clientId=${clientId}
5

Redirect User

Share the link with the user or redirect them to it for instant Nudj login.

When to Use This Method

Use This Method

  • Users are already authenticated in your platform
  • You want seamless session continuation in Nudj
  • No login screen should be shown
  • Single sign-on (SSO) experience required

Don't Use This Method

  • Users arrive directly at Nudj without authentication
  • Users need to create new accounts
  • OAuth integration is more appropriate
If users arrive directly at Nudj without being authenticated, use OAuth Integration Setup instead.

Detailed Implementation Guide

1. Retrieve Your Credentials

Navigate to Admin Panel → Settings → Organization → Developer Settings tab and copy your:
clientId
string
required
Your unique client identifier
clientSecret
string
required
Your secret key for signing tokens (keep this secure!)
apiToken
string
API token for alternative authentication method (optional)
Never expose your Client Secret in client-side code or public repositories. Always generate tokens on your backend server. Note: Nudj stores organization-level credentials. In your application, load secrets securely (e.g., environment variables or a secret manager), never from client code.

2. Generate the User Token

import { sign } from "jsonwebtoken";
import { randomUUID } from "crypto";

const userData = {
  userId: "abc123", // Unique identifier for the user
  email: "abc123@example.com", // User's email
  locale: "en", // Optional locale, defaults to "en" if not provided
  username: "John Doe", // Optional display name
  points: 100, // Optional initial points (only for new users)
};

function signUserToken(input) {
  const clientSecret = process.env.NUDJ_CLIENT_SECRET;
  if (!clientSecret) {
    throw new Error("NUDJ_CLIENT_SECRET is not set");
  }
  
  const now = Math.floor(Date.now() / 1000);
  const claims = {
    ...input,
    iss: "your-app", // Issuer
    aud: "nudj", // Audience
    iat: now, // Issued at
    nbf: now, // Not before
    jti: randomUUID(), // JWT ID for tracking
  };
  
  return sign(claims, clientSecret, { 
    algorithm: "HS256",
    expiresIn: "1h"
  });
}

const userToken = signUserToken(userData);
// Never log tokens in production - store or use securely

3. Build the Auto-Login URL

You can use either the User Token method (recommended) or the API Token method:
Critical Security Warning: Never put JWTs or API tokens in frontend redirects using window.location.href as this exposes sensitive credentials in browser history, logs, and referrer headers. Always use server-side redirects (res.redirect()) to transmit signed tokens. If client-side navigation is absolutely required, implement a secure token exchange flow using short-lived authorization codes instead of exposing JWTs directly.
Security Note: The callbackPath parameter must be a relative path starting with / and will be validated against an allowlist on the server to prevent open-redirect vulnerabilities. Full URLs or paths missing the leading slash will be rejected.

4. User Property Requirements

userId
string
required
Unique identifier for the user. This is stored as externalId in Nudj and used for account identification.
email
string
User’s email address. Must be unique per user. If omitted, Nudj generates a placeholder email in the format ${userId}@${organisationId}.com and the user can only log in via direct links (no magic link/self-login).
locale
string
Language/region code (e.g., en, fr, es). Defaults to en if not provided.
username
string
Display name shown in Nudj UI. Defaults to “anonymous” until updated by the user.
anonymousAccountId
string
Special identifier provided by Nudj to merge an anonymous session with the authenticated user account. Used for preserving user progress before authentication. This ID is typically available in the session or URL parameters when anonymous login features are enabled.
points
number
Initial points to award the user upon account creation. Only applied for new users, not updates. Creates a points transaction record automatically.

How It Works

Account Creation & Management

  • New Users
  • Existing Users
  • Anonymous Merge
When a user doesn’t exist in Nudj:
  1. Nudj receives the signed JWT token
  2. Validates the token signature using your Client Secret
  3. Creates a new account with provided details
  4. Awards initial points if specified (creates transaction record)
  5. Automatically signs the user in
  6. User lands in Nudj fully authenticated

Example Implementation Flow

1

User Login

User logs into your platform using your existing authentication system.
2

Token Generation

Your backend generates a signed JWT with the user’s information.
3

URL Construction

Your system builds the Nudj authentication URL with the token and client ID.
4

Redirect

User is redirected to the Nudj URL either automatically or via a button/link.
5

Seamless Access

User lands in Nudj fully signed in with no login screen shown.

Environment Configuration

The API Link authentication works across multiple Nudj applications:
  • Production
  • Staging
  • Development
const config = {
  domain: "yourcompany.nudj.cx",
  endpoint: "/api/link",
  protocol: "https"
};
The /api/link endpoint is available in multiple Nudj applications:
  • user app (port 3000)
  • admin app (port 4000)
  • creator-frontend app
  • api service
All applications share the same authentication logic and user database.

Complete Integration Example

Here’s a full example of implementing API Link authentication in an Express.js application:
import express from 'express';
import { sign } from 'jsonwebtoken';

const app = express();

// Middleware to check if user is authenticated in your system
function requireAuth(req, res, next) {
  if (!req.session.user) {
    return res.redirect('/login');
  }
  next();
}

// Route to redirect authenticated users to Nudj
app.get('/nudj-redirect', requireAuth, (req, res) => {
  const { user } = req.session;
  
  // Prepare user data for Nudj
  const nudjUserData = {
    userId: user.id,
    email: user.email,
    username: user.displayName,
    locale: user.preferredLanguage || 'en'
  };
  
  // Sign the token
  const userToken = sign(
    nudjUserData,
    process.env.NUDJ_CLIENT_SECRET,
    { expiresIn: '1h' }
  );
  
  // Build the Nudj URL
  const nudjDomain = process.env.NUDJ_DOMAIN; // e.g., "yourcompany.nudj.cx"
  const clientId = process.env.NUDJ_CLIENT_ID;
  const nudjUrl = `https://${nudjDomain}/api/link?userToken=${userToken}&clientId=${clientId}`;
  
  // Redirect user to Nudj
  res.redirect(nudjUrl);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Error Responses

The /api/link endpoint returns specific HTTP status codes for different error conditions:
Status CodeErrorDescription
401UnauthorizedMissing or invalid token/credentials
403ForbiddenValid token but insufficient permissions
404Not FoundDomain or organization not found
422Unprocessable EntityInvalid user data or parameters
500Internal Server ErrorServer-side processing error
Example error response:
{
  "error": "Invalid token",
  "message": "The provided user token could not be validated",
  "code": "INVALID_TOKEN"
}

Security Best Practices

Always follow these security guidelines when implementing API Link authentication:
  • Generate tokens only on your backend server
  • Never expose Client Secret in client-side code
  • Use environment variables for sensitive credentials
  • Set appropriate token expiration times (1 hour recommended)
  • Rotate Client Secrets periodically
  • Note: Organizations can have multiple Client Secrets configured
  • Validate user data before token generation
  • Ensure userId is unique and consistent
  • Sanitize email addresses and usernames
  • Handle missing optional fields gracefully
  • Verify email format if provided
  • Implement proper error handling for token generation failures
  • Provide fallback authentication methods
  • Log authentication attempts for security monitoring
  • Handle expired tokens gracefully
  • Implement retry logic with exponential backoff
  • Configure CORS to allow your domains
  • Implement CSRF protection for session management
  • Use HTTPS for all authentication requests
  • Set appropriate security headers

Troubleshooting

Problem: JWT signing throws an errorSolutions:
  • Verify Client Secret is correctly set in environment variables
  • Check that the jsonwebtoken library is properly installed
  • Ensure user data object has all required fields
  • Validate that expiration time is properly formatted
Problem: User is redirected but sees login screenSolutions:
  • Verify the token is properly URL-encoded in the link
  • Check that clientId matches your Nudj configuration
  • Ensure token hasn’t expired (check expiration time)
  • Validate domain matches your Nudj instance
Problem: Changes to user properties don’t reflect in NudjSolutions:
  • Ensure userId remains consistent (it’s the primary identifier)
  • Check that updated fields are included in the token
  • Verify token signature is valid
  • Clear browser cache and try again
Problem: User loses progress after authenticationSolutions:
  • Include the anonymousAccountId provided by Nudj
  • Ensure the ID is passed correctly in the token
  • Check timing - merge must happen during authentication
  • Contact Nudj support if issue persists

API Reference

For detailed API documentation and additional authentication methods, see:

Support

If you encounter any issues or need assistance with implementation:
  • Technical Support: Contact your Nudj account manager
  • Documentation: Visit docs.nudj.cx
  • API Status: Check status.nudj.cx
  • Community: Join the Nudj Developer Community
I