JS - /api/v3/brokerage/orders - 401 Unauthorized

Hey guys I am getting 401 when trying to create a limit order here is my script:

require('dotenv').config({ path: './api_key.env' });
const { sign } = require('jsonwebtoken');
const axios = require('axios');
const crypto = require('crypto');
const { json } = require('express/lib/response');

const key_name = process.env.COINBASE_TRADING_API_KEY;
const key_secret = process.env.COINBASE_PRIVATE_KEY.replace(/\\n/g, '\n');
const service_name = "retail_rest_api_proxy";
const algorithm = 'ES256';

function generateToken(request_path) {
    const url = 'api.coinbase.com'; // Base URL for Coinbase API
    const uri = 'GET ' + url + request_path; // Concatenate request method, URL, and path
    
    const token = sign({
        aud: [service_name],
        iss: 'coinbase-cloud',
        nbf: Math.floor(Date.now() / 1000),
        exp: Math.floor(Date.now() / 1000) + 120, // Token expiration time (2 minutes from now)
        sub: key_name,
        uri,
    }, key_secret, {
        algorithm,
        header: {
            kid: key_name,
            nonce: crypto.randomBytes(16).toString('hex'), // Generate a nonce value
        },
    });

    return token;
}

async function createOrder(orderDetails) {
    const requestPath = '/api/v3/brokerage/orders';
    const token = generateToken(requestPath); // Generate token for this specific request
    
    let body = {
        client_order_id: orderDetails.client_order_id,
        product_id: orderDetails.product_id,
        side: orderDetails.side,
        order_configuration: orderDetails.order_configuration // Use the provided order configuration directly
    };

    console.log(body);

    let config = {
        method: 'post',
        url: `https://api.coinbase.com${requestPath}`,
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        },
        data: JSON.stringify(body), // Ensure proper serialization
    };

    try {
        const response = await axios(config);
        console.log(`Order created successfully:`, response.data);
        return response.data;
    } catch (error) {
        // Improved error handling
        console.error(`Error creating order:`, error.response ? error.response.data : error.message);
        return null;
    }
}

const orderDetails = {
                        client_order_id: `buy-${currency}-${Date.now()}`,
                        product_id: `USD-${currency}`,
                     //product_id: `${currency}-USD`, <--- also tried that
                        order_configuration: {
                            "limit_limit_gtc": {
                                "base_size": lastInvestment.amount.toString(),
                                "limit_price": currentPrice.toString(),
                                //"post_only": true
                            }
                        },
                        side: "BUY",
                    };
                    await createOrder(orderDetails);

When trying to access open orders, or check for best_bid_ask all working as expected.
image

Hey @homyakny1! Thank you for being part of the forum community. 401 are client side errors. We can share some steps to troublehsoot this issue though.
Mostly these issues occur if the incorrect permissions or scopes are enabled on the key. For more details on that you can check our official docs here: Advanced Trade API Permissions | Coinbase Cloud

Apart from that, while creating the API keys, please enable account permissions for all the accounts and then try again. In case you are trying to hit the endpoint with a product ID that you have not provided the permission for, then it will throw an error.
We hope this helps. Do let us know in case you have any other concerns or questions regarding this.

He is using Cloud API key, there are no accounts permissions, is there?

Here are your problem! You are trying to create order, it is POST request but you are generating JWT for GET request.

1 Like

Thanks, thats the exact issue! All working as expected now!