
Screenshotlayer is a lightweight REST API built to deliver high-quality PNG, JPEG & GIF website screenshots at unparalleled speeds and through a simple interface. To ensure the highest possible level of image resolution, the Screenshotlayer API relies on a powerful rendering engine capable of processing, storing, and returning all sorts of website content within just a few seconds.
In this blog post, we’ll take a look at how we can easily build our own website screenshot CDN in NodeJS using the Screenshotlayer API.
Table of Contents
What are the minimum Node dependencies that are required for this project?
As part of the CDN development process, we will initially require express
and fs
Node packages to seamlessly achieve the development experience. If these packages are already part of node_modules
in your Node project then well and good. If not, go ahead and install these two dependencies using npm
.
Once installed, import the dependencies as follows.
1 2 |
var express = require('express'); var fs = require('fs'); |
How can I create a REST endpoint for taking screenshots with Screenshotlayer?
In this section, we’ll create a REST API endpoint /full-height-screenshot
in our Node application that will internally hit the Screenshotlayer API endpoint to get the screenshot of the website passed in the request payload.
The Screenshotlayer API endpoint URL looks as follows.
1 2 3 4 |
endpoint = http://api.screenshotlayer.com/api/capture ? access_key = YOUR_ACCESS_KEY & url = req.params[url] & fullpage = 1 |
Once we have the endpoint URL ready, let’s hit the API endpoint to get the screenshot of the requested website. The following code snippet can do this job.
1 2 3 4 5 6 7 |
try { const apiResponse = await fetch(endpoint) console.log('Successfully retrieved screenshot') } catch (err) { console.log(err) res.status(500).send('Something went wrong') } |
Next up, we need to save this screenshot as an image file on our server. Why are we doing that? Well, hold on a bit, it will get clearer in the next section.
We can save the screenshot as an image on our server as follows.
1 2 3 4 5 6 7 8 |
let uniqueFileName = fullHeight + req.params['url'] + '.png' fs.writeFile(uniqueFileName, apiResponse, function (err) { if (err) { console.log(err); } else { console.log('Successfully saved screenshot'); } }); |
Now that we have the individual components ready, let’s combine them under our /full-height-screenshot
endpoint to serve it to the client over a network.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
app.post('/full-height-screenshot', (req, res) => { endpoint = http://api.screenshotlayer.com/api/capture ? access_key = YOUR_ACCESS_KEY & url = req.params[url] & fullpage = 1 try { const apiResponse = await fetch(endpoint) console.log('Successfully retrieved screenshot') let uniqueFileName = fullHeight + req.params['url'] + '.png' fs.writeFile(uniqueFileName, apiResponse, function (err) { if (err) { console.log(err); } else { console.log('Successfully saved screenshot'); } }); res.set({'Content-Type': 'image/png'}) res.sendFile(uniqueFileName) } catch (err) { console.log(err) res.status(500).send('Something went wrong') } }); |
How can I use the cached API results returned from Screenshotlayer?
Up until here, we are hitting the Screenshotlayer API every time we get a request on our server. This increases our server response time as numerous secondary API calls are being made against each API request.
We can optimize this process by using caches. In the above code snippets, we have already implemented the caching mechanism by saving the API results as an image file on our server, but now, let’s actually use these image files to optimize the request-response cycle.
Using the following piece of code, we can check whether the file already exists or not. If the file exists for less than 24 hours, we’ll return the cached file. Otherwise, we’ll make a fresh API call and cache its results again.
1 2 3 4 5 6 7 8 9 10 11 12 |
var isFilePresent = fs.existsSync(uniqueFileName) var hour = null; if (isFilePresent) { var stats = fs.statSync(uniqueFileName); hours = (new Date().getTime() - stats.mtime) / (1000 * 60 * 60); } if (isFilePresent && hours > 24) { // Hit the Screenshotlayer API } else { // Return the saved file content } |
Our all-in-all REST endpoint with caching looks something like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
app.post('/full-height-screenshot', (req, res) => { let uniqueFileName = fullHeight + req.params['url'] + '.png' try { var isFilePresent = fs.existsSync(uniqueFileName) var hour = null; if (isFilePresent) { var stats = fs.statSync(uniqueFileName); hours = (new Date().getTime() - stats.mtime) / (1000 * 60 * 60); } if (isFilePresent && hours > 24) { // Hit the Screenshotlayer API endpoint = http://api.screenshotlayer.com/api/capture ? access_key = YOUR_ACCESS_KEY & url = req.params[url] & fullpage = 1 const apiResponse = await fetch(endpoint) console.log('Successfully retrieved screenshot') fs.writeFile(uniqueFileName, apiResponse, function (err) { if (err) { console.log(err); } else { console.log('Successfully saved screenshot'); } }); res.set({'Content-Type': 'image/png'}) res.sendFile(uniqueFileName) } else { // Return the saved file content res.set({'Content-Type': 'image/png'}) res.sendFile(uniqueFileName) } } catch (err) { console.log(err) res.status(500).send('Something went wrong') } }); |
How can I serve the screenshot REST endpoint using Express?
Now that we have the main CDN engine set up, it’s time to serve it and open our server connection to listen to API requests. Using express, we can easily achieve this by writing the following lines of code.
1 2 3 4 |
var port = 3000; express.listen(port, () => { console.log(`Node server listening on port ${port}...`); }) |
As you can see, creating your own website screenshot CDN in NodeJS using Screenshotlayer is pretty simple and quick. Not only that, Screenshotlayer is reliable and easy on your budget to help you enable a diverse digital ecosystem that focuses on user experience. Moreover, the free plan of Screenshotlayer is an ideal choice for experimentation, trials, and proof of concepts.
Head over to Screenshotlayer and get creative with your custom screenshot REST endpoints.