Create your own screenshot API using Puppeteer + ExpressJS

Ankit Mishra
3 min readJan 7, 2020

First a quick intro to the technologies we’re going to use -

Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium.

Express is a minimalist web framework for Node.js, that means it takes care of the heavy lifting and makes it super easy to create web services on top of NodeJS.

Let’s get started!

Step 1 — Setup

  • Install node (it will be our server), any text editor (I used VSCode)
  • In a new folder, open command prompt, and type npm init, keep pressing enter to choose defaults. Now you should see a new file package.json, which looks like this -
  • Let’s install dependencies —
npm i --save puppeteer express

This should update your package.json file by adding dependencies and create a new folder node_modules. Now we’re all set for next step.

Step 2 — Create a super simple web service
Create a file index.js, and paste below code.

To run this server, open command prompt in the folder and run bellow command -

node index.js

Now open http://localhost:3000/ in your browser and you should see “Hello world!”. But that’s not what we want, so now we need to replace lame text with an high quality screenshot from a live website.

Step 3 — Take screenshot

This is the part where the Puppeteer magic happens, now we use it’s API to click a screenshot and send it back to client. Let’s modify index.js as below

Note how we replaced res.send('Hello world!'); with res.send(image);

Go back to the command prompt kill the server and restart the server by using the same command as we used to start it — node index.js

Again open http://localhost:3000/ and now you should see something like this -

Step 4 — Make URL dynamic
But we don’t want to always get screenshot from http://google.com, do we ? Instead we want it to be dynamic. One way to do it is to add a query parameter. With expressJS this can be done using request.query.<paramname> syntax. Now we just need to replace page.goto("http://google.com") with page.goto(request.query.url).

Final source code

Restart the server again and, now you can pass any URL you wish e.g. — http://localhost:3000/?url=http://amazon.com

What’s next ?
This service can be hosted on a cloud service provider like Heroku, Google Cloud etc. And can be extended with several options like —
- screenshots for devices (e.g iPad, Pixel)
- convert page to PDF
- to return different image formats (jpeg, png)
- and many more…

Puppeteer screenshot API documentation can be accessed here for extensive list of option.

Thanks for reading! Would love to hear your feedback/suggestions and if you found the post helpful.

--

--