Developers

    Create a UPCS Embed Session in Node.js

    Node.js example for creating a UPCS embed session on your server with fetch, including error handling and what to return to the browser.

    Updated 14 October 2026 · 2 min read

    Creating an embed session from Node.js needs only the built-in fetch (Node 18 or later) and your API key from an environment variable. The function below returns the session data and throws a useful error when UPCS responds with a failure.

    A reusable function

    // upcsSession.js
    const UPCS_BASE = 'https://api.upcs.io/api';
    
    export async function createEmbedSession(origin, ttl) {
      const body = { origin };
      if (ttl) body.ttl = ttl; // 60-3600 seconds
    
      const res = await fetch(`${UPCS_BASE}/v1/embed/sessions`, {
        method: 'POST',
        headers: {
          'x-api-key': process.env.UPCS_API_KEY,
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify(body),
      });
    
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.success === false) {
        const err = new Error(data.message || `UPCS request failed (${res.status})`);
        err.status = res.status;
        err.code = data.code;
        throw err;
      }
      return data; // session_token, expires_at, embed_url
    }
    

    Using it in a route

    A framework-specific version is in the Express example. The essential idea is that your route calls the function and returns only the token:

    const session = await createEmbedSession('https://shop.example.com');
    res.json({ session_token: session.session_token, expires_at: session.expires_at });
    

    Use a fixed, configured origin rather than copying a value from the request, so a visitor cannot ask your server to create sessions for arbitrary origins.

    Handling failures

    Check err.code and err.status:

    • origin_not_allowed (403): register the origin under Allowed origins.
    • partner_required (403): the key is not linked to a partner account; use a key created in the partner panel.
    • 401 without a code: the key is missing, invalid or disabled; see API key rotation.
    • 422: the origin or ttl failed validation.

    Return a generic message to the browser and log the detail on the server.

    Keep the key private

    Load UPCS_API_KEY from the environment or a secrets manager, never from a file that is committed or served to the browser. More in securing your UPCS API key. For the browser half of the flow, see embedding the map on a website.

    Frequently asked questions

    Do I need a UPCS package for Node.js?

    No. There are no official SDKs; a plain HTTPS request with the x-api-key header is all that is required.

    Should I return the whole API response to the browser?

    Return only what the page needs, normally the session_token. Keep the API key and any internal details on the server.