Logo

dev-resources.site

for different kinds of informations.

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

Published at
10/21/2024
Categories
ubuntu
node
puppeteer
Author
dailysandbox
Categories
3 categories in total
ubuntu
open
node
open
puppeteer
open
Author
12 person written this
dailysandbox
open
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!

puppeteer Article's
30 articles in total
Favicon
How to Web Scrape with Puppeteer: A Beginner-Friendly Guide
Favicon
Running Puppeteer on a Server: A Complete Tutorial
Favicon
Collect All Requested Images on a Website Using Puppeteer
Favicon
Automate Web Testing in C#: A Guide with PuppeteerSharp and SpecFlow
Favicon
A step-by-step guide to setting up a Puppeteer screenshot API on Ubuntu
Favicon
Elevate Your Web Scraping with These Puppeteer Alternatives
Favicon
Creating a Next.js API to Convert HTML to PDF with Puppeteer (Vercel-Compatible)
Favicon
How to configure Swiftproxy proxy server in Puppeteer?
Favicon
installing google chrome in docker
Favicon
Code Against the Clock: Creating the class hunter
Favicon
Writing integration tests with jest and puppeteer
Favicon
Puppeteer Vs Playwright: Scrape a Strapi-Powered Website
Favicon
Mengirim Pesan WhatsApp dengan JavaScript
Favicon
Headless Browser – A Stepping Stone Towards Developing Smarter Web Applications
Favicon
Puppeteer junior
Favicon
Converting HTML web pages into PDF
Favicon
How to Scrape With Headless Firefox
Favicon
Top 5 Puppeteer Alternatives for Node.js
Favicon
How to generate PDF's with Puppeteer on Vercel in 2024
Favicon
Simplify PDF Generation in Node.js with html-to-pdf-pup
Favicon
How to do Web Scraping with Puppeteer and NodeJS in 2024 | Puppeteer tutorial
Favicon
Sometimes things simply don't work
Favicon
User browser vs. Puppeteer
Favicon
WebAuthn E2E Testing: Playwright, Selenium, Puppeteer
Favicon
Mastering Request Interceptions in Puppeteer
Favicon
How to grab all titles of products from an Amazon page
Favicon
Testing web components
Favicon
Rendering PDF from URLs and HTML input using express js
Favicon
Login with Puppeteer and re-use cookies for another window
Favicon
How to download and upload files in Puppeteer

Featured ones: