DEV Community

Cover image for A step-by-step guide to setting up a Puppeteer screenshot API on Ubuntu
Art
Art

Posted on • Originally published at blog.dailysandbox.pro

A step-by-step guide to setting up a Puppeteer screenshot API on Ubuntu

I needed to setup an API end-point that, when passed a URL would take a screenshot of the website. This guide covers the setup of a Node.js application using Puppeteer, which will act as an API for capturing screenshots.

1. Update and Upgrade System

First, update and upgrade your system to make sure all the packages are up-to-date.

sudo apt update && sudo apt upgrade -y
Enter fullscreen mode Exit fullscreen mode

2. Install Node.js and NPM

You’ll need Node.js and npm to run Puppeteer. Install them using the official Node.js repository.

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

3. Create a Project Directory

Create a directory for your Puppeteer project.

mkdir puppeteer-screenshot-api
cd puppeteer-screenshot-api
Enter fullscreen mode Exit fullscreen mode

4. Initialize a Node.js Project

Initialize a new Node.js project.

npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file with default values.

5. Install Required Dependencies

Install the necessary dependencies for Puppeteer and Express to set up the API.

npm install express puppeteer
Enter fullscreen mode Exit fullscreen mode

6. Write the Puppeteer Screenshot API

Create a file named index.js in your project directory and add the following code:

const express = require('express');
const puppeteer = require('puppeteer');
const app = express();
const port = 3000;

// Screenshot endpoint
app.get('/screenshot', async (req, res) => {
    const { url } = req.query;

    if (!url) {
        return res.status(400).send('Please provide a URL');
    }

    try {
        const browser = await puppeteer.launch({
            args: ['--no-sandbox', '--disable-setuid-sandbox']  // Necessary for running Puppeteer on Ubuntu
        });
        const page = await browser.newPage();
        await page.goto(url, { waitUntil: 'networkidle2' });
        const screenshot = await page.screenshot({ fullPage: true });

        await browser.close();

        // Set content type and send screenshot
        res.setHeader('Content-Type', 'image/png');
        res.send(screenshot);
    } catch (error) {
        console.error(error);
        res.status(500).send('Error capturing screenshot');
    }
});

app.listen(port, () => {
    console.log(`Puppeteer Screenshot API is running on http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

7. Run the Puppeteer API

Run the server using Node.js:

node index.js
Enter fullscreen mode Exit fullscreen mode

The server should now be running on http://localhost:3000. You can test it by visiting the following URL in your browser:

http://localhost:3000/screenshot?url=https://example.com
Enter fullscreen mode Exit fullscreen mode

It will return a PNG screenshot of the provided URL.

8. Install Puppeteer Dependencies

Sometimes Puppeteer requires additional dependencies for Ubuntu. Install them by running:

sudo apt install -y libxshmfence1 libasound2 libgbm-dev libgtk-3-0 libnss3 libxss1 libxtst6 xdg-utils
Enter fullscreen mode Exit fullscreen mode

9. Running Puppeteer as a Background Service (Optional)

If you want the Puppeteer API to run in the background and automatically start after a reboot, you can set it up as a systemd service.

  1. Create a service file for your Puppeteer API.
   sudo nano /etc/systemd/system/puppeteer-screenshot.service
Enter fullscreen mode Exit fullscreen mode
  1. Add the following content to the file:
   [Unit]
   Description=Puppeteer Screenshot API
   After=network.target

   [Service]
   ExecStart=/usr/bin/node /path/to/your/puppeteer-screenshot-api/index.js
   Restart=on-failure
   User=your-username
   Environment=NODE_ENV=production

   [Install]
   WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

Replace /path/to/your/puppeteer-screenshot-api/index.js with the actual path of your project.

  1. Enable and start the service:
   sudo systemctl enable puppeteer-screenshot
   sudo systemctl start puppeteer-screenshot
Enter fullscreen mode Exit fullscreen mode
  1. Check the status:
   sudo systemctl status puppeteer-screenshot
Enter fullscreen mode Exit fullscreen mode

10. Test the API

You can now send requests to your server to capture screenshots. Use curl or your browser:

curl "http://localhost:3000/screenshot?url=https://example.com" --output example.png
Enter fullscreen mode Exit fullscreen mode

This will save the screenshot as example.png.

For more tips on web development, check out DailySandbox and sign up for our free newsletter to stay ahead of the curve!

Top comments (0)