Set a Canonical URL in Node.JS

Cloudmersive
2 min readJul 23, 2021

Need to set the canonical link of an HTML document, but don’t want to deal with the additional coding? We’ve got you covered. In this tutorial we will demonstrate how you can use an API to set a rel=canonical HTML tag in a specific HTML document. By solidifying the canonical URL, you will not only ensure the correct version of your page is found by search engines, but you can also add it to a sitemap (another great SEO tool).

Let’s begin by running this command to install the package:

npm install cloudmersive-convert-api-client --save

Or, we could add this snippet to our package.json:

"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}

This brings us to the function call, which can be performed by inputting the HTML file or file URL, the canonical URL to set, and your API key into the following code:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.EditHtmlApi();var canonicalUrl = "canonicalUrl_example"; // String | The HTML canonical URL to set.var opts = {
'inputFile': Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer), // File | Optional: Input file to perform the operation on.
'inputFileUrl': "inputFileUrl_example" // String | Optional: URL of a file to operate on as input.
};
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.editHtmlHtmlSetRelCanonical(canonicalUrl, opts, callback);

And that’s it — your work is done. If you need to obtain an API key, you can do so by registering for a free account on the Cloudmersive website; this provides 800 monthly calls across any of our APIs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.