# Example: Registering a User via Internal API (JavaScript)

The following JavaScript example demonstrates how to:

1. Request a message and nonce from the internal API.
2. Sign the message using a user's private key.
3. Send a registration request with the signature, public key, and nonce.

> This example uses `tweetnacl` for signing and `axios` for HTTP requests.

```bash
npm install tweetnacl bs58 axios
```

```js
const nacl = require('tweetnacl');
const bs58 = require('bs58');
const axios = require('axios');

// Replace with your API key and private/public keys
const API_KEY = 'your-api-key-here';
const PRIVATE_KEY_BASE58 = 'your-user-private-key';
const PUBLIC_KEY_BASE58 = 'your-user-public-key';

async function registerUser() {
  try {
    // 1. Get message and nonce
    const getMessageRes = await axios.get('https://BASE_URL/v1/internal/auth/get-message', {
      headers: { 'x-api-key': API_KEY },
    });

    const { message, nonce } = getMessageRes.data;

    // 2. Sign the message
    const privateKeyUint8 = bs58.decode(PRIVATE_KEY_BASE58);
    const messageUint8 = new TextEncoder().encode(message);
    const signature = nacl.sign.detached(messageUint8, privateKeyUint8);
    const signatureBase64 = Buffer.from(signature).toString('base64');

    // 3. Send registration request
    const registerRes = await axios.post(
      'https://api.yourdomain.com/v1/internal/auth/register',
      {
        publicKey: PUBLIC_KEY_BASE58,
        signature: signatureBase64,
        nonce: nonce,
      },
      {
        headers: {
          'x-api-key': API_KEY,
          'Content-Type': 'application/json',
        },
      }
    );

    console.log('User registration successful:', registerRes.data);
  } catch (error) {
    console.error('Registration failed:', error.response?.data || error.message);
  }
}

registerUser();
```

## Notes

* The private key must be in raw Uint8Array format (not PEM).
* Make sure the public/private keys match.
* Use secure key management when handling private keys.
