Puppeteer is a library developed for Node.js that provides an API to control Chrome or Chromium. It is specialized for operating Headless Chrome and is often used for test automation. The official website is as follows.
PuppeteerPuppeteer is a JavaScript library which provides a high-level API to control Chrome or Firefox over the DevTools Protocol or WebDriver BiDi. Puppeteer runs in the headless (no visible UI) by default
Here, we will introduce the steps to deploy a Next.js sample using Puppeteer to Vercel.
Create a Project
First, we will create a sample of Puppeteer that can be used with Next.js. The prerequisites for this document are as follows:
Next.js 14.2.18
Pages Router
Node.js v20
macOS
Google Chrome
When running locally, it is assumed that Google Chrome is installed, and it will operate in Headless mode to take screenshots.
Create a new Next.js project.
This time, we selected as follows.
Add the puppeteer package.
This time, we will use puppeteer as an API to get images by specifying a URL. Therefore, create a file src/pages/api/screenshot.ts and add the following code.
Change the code of the Next.js top page as follows.
Delete all sample styles listed in the stylesheet /src/styles/globals.css.
Run the above state.
Enter the URL and press the button to take a screenshot. It was displayed as an image as follows.
Deploy to Vercel
In the above, we used Google Chrome installed locally, but Chrome is not installed in the Vercel environment, so it does not work as it is.
Therefore, this time, we will use a package called @sparticuz/chromium. This is a package of Chromium that can be used in a Serverless environment.
Change the API in /src/pages/api/screenshot.ts to use the above chromium in the Vercel environment as follows.
After the above changes, deploy to Vercel and check the operation. When you enter the URL and execute it, it will be as follows.
Actually, @sparticuz/chromium does not include Japanese fonts by default, so when you refer to a Japanese page, the content is not displayed correctly on the page.
This time, we want to display Japanese as well, so we will add processing to display Japanese in /src/pages/api/screenshot.ts. Specifically, add a definition for the style and wait for 1 second before taking the screenshot to apply it.
After the above code changes, deploy to Vercel again and run the test. Successfully took a screenshot.
Summary
This time, we deployed a simple Next.js app using Puppeteer to Vercel. Regarding the part where Japanese cannot be displayed, we were able to apply Japanese fonts to the screenshot by using the package function. It will probably work similarly for other languages as well.
This sample code is available at the following URL. We also share the code for App Router.