Skip to main content
Crusoe Support Help Center home page
Crusoe

How-To Handle Special Characters in API Keys (TypeScript & JSON)

Rishabh Sinha
Rishabh Sinha
Updated

Last Updated: [Mar 15, 2026]

Introduction

Crusoe Inference API keys utilise high-entropy strings that often include the $ character. In TypeScript/Node.js environments, particularly when keys are passed through JSON configuration strings or shell-injected environment variables, these characters can be "mangled." This results in persistent 401 Unauthorised errors even with a valid key. This guide demonstrates how to use Base64 encoding to ensure your credentials remain intact across your entire deployment pipeline.

Prerequisites

  • Crusoe Inference API Key: Generated via the Security > Inference API Key tab in the Crusoe Cloud Console.

Step-by-Step Instructions

  1. Identify the "Character Mangling" Risk

    Standard environment variables and JSON strings treat the $ character as a special operator:

    • Shell Expansion: If stored in an .env file or shell without single quotes, $2a might be interpreted as a variable and replaced with an empty string.
    • JSON Parsing: Escaping characters with backslashes (\$) inside a JSON-formatted environment variable often triggers SyntaxError: Bad escaped character during JSON.parse().
  2. Encode the Key to Base64

    To bypass these limitations, convert your raw API key into a Base64-encoded string. Base64 uses only safe alphanumeric characters (A-Z, a-z, 0-9, +, /, =), which are never interpreted as variables.

    Run this in your terminal to generate the safe string:

    echo -n 'your$raw$crusoe$api$key' | base64

    Note: The -n flag is critical to prevent encoding a trailing newline.

  3. Store the Encoded String in your Environment

    Instead of storing the raw key, store the Base64 output in your secret manager or .env file.

    Example: CRUSOE_API_KEY_B64="S3J1c29lX0FQSV9LZXlfRXhhbXBsZQ"

  4. Implement the Decoder in TypeScript

    Use Node.js Buffer class to decode the key at runtime before initialising the OpenAI client. This ensures the literal, original key is passed to the Crusoe Gateway.

    import OpenAI from 'openai';
    
    // 1. Retrieve the Base64 string from your environment
    const base64Config = process.env.CRUSOE_API_KEY_B64;
    
    // 2. Decode the Base64 string to a UTF-8 JSON string
    const jsonString = Buffer.from(base64Config, 'base64').toString('utf-8');
    
    // 3. Parse the JSON string to extract the literal apiKey
    const credentials = JSON.parse(jsonString);
    const apiKey = credentials.apiKey;
    
    // 4. Initialize the OpenAI client with the literal key
    const client = new OpenAI({
      baseURL: 'https://managed-inference-api-proxy.crusoecloud.com/v1/',
      apiKey: apiKey,  
    });
    
    // 5. Execute your inference request
    client.chat.completions
      .create({
        model: 'deepseek-ai/DeepSeek-V3-0324',
        messages: [
          {
            "role": "user",
            "content": "Hello, how are you?"
          }
        ],
        temperature: 1,
        top_p: 0.95,
        frequency_penalty: 0,
        presence_penalty: 0,
      })
      .then((response) => console.log(response));

Example

Scenario: GitHub Actions Secrets

If you are deploying to a platform that manages secrets, you may find that providing raw keys with $ signs leads to intermittent authentication failures.

  • The Fix: By providing the CRUSOE_API_KEY_B64 variable as shown above, your application logic handles the "un-mangling" of the key in memory, safely tucked away from shell interpreters.

Common Issues and Resolutions

  • Issue: AuthenticationError: 401 Incorrect API key provided.
    • Resolution: This is usually due to a hidden newline character in the Base64 string. Re-run your encoding step using echo -n to ensure no trailing characters are included.
  • Issue: SyntaxError: Unexpected token... in JSON at position X.
    • Resolution: This indicates that the Base64 string was decoded into invalid JSON. Verify that your original string (before encoding) was valid JSON: {"apiKey": "..."}.

Additional Resources

Related to

Was this article helpful?

0 out of 0 found this helpful

Still need help?

Our support team is ready to assist you with any questions.

Have more questions? Submit a request

Recently Viewed

Comments

0 comments

Article is closed for comments.