Skip to content

Create Dynamic Screenshots of Websites

Embedding URL screenshots into a web application the traditional way be stressful and time-consuming. This is because you have to visit the URL, install a screenshot capture solution that takes the screenshot, and maybe edit it using a graphic editor before embedding it into the application.

Among the wide range of media services Cloudinary provides is the URL2PNG add-on. This screenshots-as-a-service helps generate screenshots of URLs on-the-fly and makes the whole editing and transformation process fast and easy. A common use of this service may be seen in blogs and popular news sites, where screenshots of websites that have been shared are embedded into posts. For example, Google and other popular search engines like Bing and Yahoo! display screenshots of websites in search results.

In this article, we’ll walk through setting up Cloudinary’s URL2PNG add-on and generating static screenshots of websites using a simple Next.js application. Let’s begin!

Here is a link to the demo on CodeSandbox.

Let’s create a new Next.js application by running this command:

    npx create-next-app url-to-png

The create-next-app is a Next.js bootstrapping tool, which helps avoid the hassle of manually setting up a Next.js application. Once that’s done installing, you can cd into your directory using this command:

    cd url-to-png

Now run this command in your terminal to install the dependencies we need for this project.

    npm install cloudinary axios dotenv

We will be using the Cloudinary node SDK to generate screenshots, which will be sent to the frontend, while axios is the HTTP client we will use to communicate with our serverless function.

Before proceeding to the next section, let’s create a file called getImage.js inside the api folder, which will hold our serverless function. We won’t be creating a separate folder for components, as most of the components in our application will be contained in the Home component in the index.js file.

We need to complete a few steps before we can start enjoying the prowess offered by the Cloudinary URL2PNG add-on. Click here to create an account with Cloudinary, or login if you already have one.

You should see a dashboard after a successful signup or login. The dashboard displays your Cloudinary credentials. Let’s set up our environment variables. Create a root-level file called .env and add the following variable to it:

    CLOUD_NAME=ADD-YOUR-CLOUD-NAME
    API_KEY=ADD-YOUR-API-KEY
    API_SECRET=ADD-YOUR-API-SECRET

Next, we need to register for the Cloudinary URL2PNG add-on before using the tool. Click on the Add-ons navigation item in the navigation bar.

You should see a page with a list of all the available add-ons; scroll up to locate the URL2PNG add-on and click it.

It is also important to note that this add-on has different subscription plans with various offers. Of course, we will be using the free plan in this application, and it gives us 50 screenshots per month. However, you can subscribe to any plan based on your needs by clicking the preferred link.

Our application will comprise mainly of two major components. The index.js file holds the frontend code for getting the URL and rendering the screenshots, and then the getImage.js file contains the backend logic for configuring Cloudinary and generating the screenshots.

Add the following to the index.js file in /pages/ directory:

    import { useState } from 'react';
    import styles from '../styles/Home.module.css';
    import axios from 'axios';
    export default function Home() {
      //.....
      return <div className={styles.main}></div>;
    }
Code language: JavaScript (javascript)

In the code above, we imported the React useState() hook, which will be used to hold stateful values. We also imported styles from the Home.module.css file using the CSS modules approach to styling. Lastly, we brought in axios, which will be used to communicate with our serverless function.

For the backend, add the following to the getImage.js file in the /pages/api/ directory:

    const cloudinary = require('cloudinary').v2;
    cloudinary.config({
      //...........
    });
    export default function handler(req, res) {
      //.........
    }
Code language: JavaScript (javascript)

After abstractly defining the components of our application, we’ll proceed in the following sections by going over these steps to implement the Cloudinary URL2PNG add-on in the application.

  • Develop the user interface and get the user’s URL
  • Create the logic to generate screenshots
  • Send the URL to the backend and embed the screenshot

Add the following to your index.js file in the /pages/ directory:

    import { useState } from 'react';
    import Image from 'next/image';
    import styles from '../styles/Home.module.css';
    import axios from 'axios';
    export default function Home() {
      const [screenShotUrl, setScreenShotUrl] = useState('');
      const [url, setUrl] = useState('');
      const handleOnGenerate = () => {
        console.log('Yes, it worked');
      };
      const setInputUrl = (e) => {
        setUrl(e.target.value);
      };
      return (
        <div className={styles.main}>
          <input
            type="text"
            onChange={setInputUrl}
            value={url}
            placeholder="Enter Url or paste Url"
          ></input>
          <button onClick={handleOnGenerate}>Generate Snapshot</button>
          <div className={styles.imageWrapper}>
            {!!screenShotUrl ? <img src={screenShotUrl} alt="screenshot" /> : null}
          </div>
        </div>
      );
    }
Code language: JavaScript (javascript)

We created two state variables, url and screenShotUrl, to store the URL entered by the user and the generated screenshot link, respectively. We then rendered a controlled input element and set its value to the value stored in the url state variable.

We also returned a button with a yet-to-be-defined handleOnGenerate function and a wrapper div to hold the generated screenshot.

To conclude this section, we need to add some styles to our application. Replace the styles in your Home.module.css file in the /styles/ directory with the following:

    .main {
      display: flex;
      flex-direction: column;
      width: 800px;
      max-width: 80%;
      align-items: center;
      margin: 4rem auto;
    }
    .main > input {
      width: 100%;
      padding: 0.6rem 1rem;
      border: 1px solid rgba(0,0,0,.1);
      margin: 1rem 0;
    }
    .main > input:focus {
      outline: none;
    }
    .main > button {
      padding: 0.6rem 1rem;
      background: green;
      border: none;
      color: #fff;
      font-size: 1rem;
      font-family: monospace;
      cursor: pointer;
    }
    .imageWrapper {
      width: 100%;
      height: 50vh;
      border: 1px solid rgba(0,0,0,.1);
      margin: 2rem 0;
    }
    .imageWrapper > img {
      width: 100%;
      object-fit: cover;
    }
Code language: CSS (css)

Open your getImage.js file, and update its content with the following:

    const cloudinary = require('cloudinary').v2;
    require('dotenv').config();
    
    cloudinary.config({
      cloud_name: process.env.CLOUD_NAME,
      api_key: process.env.API_KEY,
      api_secret: process.env.API_SECRET,
      secure: true,
    });
    
    export default function handler(req, res) {
      const imageShot = cloudinary.image(req.body.url, {
        type: 'url2png',
        sign_url: true,
      });
      res.status(200).json({ name: imageShot });
    }
Code language: JavaScript (javascript)

We set the configuration parameters using our Cloudinary credentials. We created a constant called imageShot that holds the generated screenshot link, which is then sent as a JSON object response.

Update your index.js file with the following code:

    import { useState } from 'react';
    import Image from 'next/image';
    import styles from '../styles/Home.module.css';
    import axios from 'axios';
    export default function Home() {
      const [screenShotUrl, setScreenShotUrl] = useState('');
      const [url, setUrl] = useState('');
      const getImageEl = async () => {
        const resp = await axios.post('/api/getImage', {
          url: url,
        });
        const responseUrl = /'(.+)'/.exec(resp.data.name);
        setScreenShotUrl(responseUrl[1]);
      };
      const handleOnGenerate = () => {
        getImageEl();
      };
      // Remove this function
      const handleOnGenerate = () => {
        console.log('Yes, it worked');
      };
      const setInputUrl = (e) => {
        setUrl(e.target.value);
      };
      return (
        <div className={styles.main}>
          //...
        </div>
      );
    }
Code language: JavaScript (javascript)

The code adds an a getImageEl() function that is called when the handleOnGenerate() get triggered. getImageEl() is an asynchronous function that makes an HTTP post request to the serverless function, while passing the URL as payload.

A regular expression is then executed on the response data to extract the generated screenshot link, which is then stored in state. We also embedded the generated screenshot into our application by passing the link generated as the src value to an img tag.

The gif below shows the demo:

You can also add some transformations to the screenshots generated using conventional Cloudinary techniques. To learn about adding transformation to screenshots, click here.

Find the complete project here on GitHub.

The Cloudinary URL2PNG add-on offers great URL screenshot generation and transformation capabilities that are remarkably better than the traditional way of doing it and offer excellent flexibility in integrating with various applications.

Resources You May Find Useful

Back to top

Featured Post