DEV Community

Stanislav Berkov
Stanislav Berkov

Posted on

node-fetch request having custom certificate

While developing you have to deal with internal servers that use enterprise SSL certificate. Nodejs has its own certificate storage. Thereby you need to provide certificates explicitly.

const fetch = require("node-fetch").default;
const https = require("https");
const fs = require("fs");

const ca = fs.readFileSync("./mozilla-ca-plus-custom.pem").toString();
const agent = new https.Agent({ ca });

async function main() {
    const res = await fetch("https://server.local/master/api2/v1/UserPages", {
        "headers": {
            "accept": "application/json, text/plain, */*",
            "accept-language": "en-US,en;q=0.9,ru;q=0.8",
            "authorization": "Bearer 1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3cGZlX3VzZXJfaWQiOiIzZTQwNjZkMi04Mjg2LTQyNzktOWFjNC04YzNlNTNhMjNjMjYiLCJ3cGZlX2xvZ2luIjoic2JlcmtvdiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6WyJNYXN0ZXJBZG1pbiIsIkNvbnRlbnRFZGl0b3IiLCJUcmFuc2xhdG9yIiwiTW9uaXRvciJdLCJzdWIiOiI0YTBiZGQyMC01YzJkLTI1NGUtYTE2ZC03YjY1MDVlZjI1NTgiLCJuYmYiOjE3MDE0MDk3NjgsImV4cCI6MTczMjk0NTc2OCwiaXNzIjoiV3BmZVNlcnZlciIsImF1ZCI6IldwZmVTZXJ2ZXIgQ2xpZW50cyJ9.k_aaDTeJUyxYv--KBVJYZCBSAHiG_eGHACz2dqCvr5w",
            "content-type": "application/json",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
        },
        "body": "{}"
        "method": "PUT",
        agent
    });

    const text = await res.text();
    console.log(text);
}

main();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)