Using an SSL Certificate to Make a Secure HTTP Request in Node.JS
I’m documenting this only because I had some difficulty finding info online… the API docs tell you what you need, but it took me a couple hours to get things working and a little known bug that threw my work off track.
So say you want to make a secure request to a website, perhaps a secure API call (as is most common with payment gateway APIs) and you’re using nodejs… what do you do? Assuming you already have a private key and an SSL Certificate handy and that you’ve compiled nodejs with ssl support, I’ll show you how in the following steps.
First, place the cert somewhere that your script can access it from, I usually prefer a location like ./certs. Make absolutely positively sure that you have no trailing newlines at the end. You also have the option of embedding it within your script (I’ve seen it done) but I believe this is a poor practice. Still, you have the option of doing that.
Given that your script/app/module is located in the same directory as the certs directory, load the contents of both keys into memory and use the crypto module to create the credentials.
With the credentials now available, we can set up the client and make a request
That is, createClient(port, host, secure, credentials). If everything goes well you should be able to make a request. One thing to watch out for is a trailing newline at the end of your key or cert. Often times I add key.replace(/\n$/, '') to it just to be safe.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!













