Deploying Playwright
Playwright is an open-source end-to-end test automation framework developed by Microsoft. It supports multiple browsers (Chromium, Firefox, WebKit) and can execute fast and reliable tests. Playwright offers many features, including cross-browser testing, screenshots, and PDF generation.
The official Playwright website is as follows:
This document introduces the steps to deploy a Next.js sample using Playwright to Vercel and take screenshots.
Create a Project
First, create a sample using Playwright 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 screenshots will be taken by running Google Chrome in Headless mode.
-
Create a new Next.js project.
The selections were made as follows:
-
Add the playwright package.
-
Use playwright as an API to capture images by specifying a URL. Create the file
src/pages/api/screenshot.ts
and add the following code. -
Modify the code of the Next.js top page as follows.
-
Remove all sample styles listed in the stylesheet
/src/styles/globals.css
.
Run the following command to execute.
Enter the URL, press the button, and take a screenshot. It was displayed as an image as follows.
Deploy to Vercel
In the above, Google Chrome installed locally was used, but Chrome is not installed in the Vercel environment, so it does not work as 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.
The steps are as follows.
-
Install
@sparticuz/chromium
. -
Modify 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. Enter the URL and execute it, and it will be as follows.
Actually, @sparticuz/chromium
does not include Japanese fonts by default, so when referring to a Japanese page, the content is not displayed correctly on the page.
This time, to display Japanese, add processing to display Japanese in /src/pages/api/screenshot.ts
. Specifically, add definitions regarding styles and wait for 1 second before taking a screenshot to apply them.
After the above code changes, redeploy to Vercel and run the test. Successfully took a screenshot.
Summary
This time, we deployed a simple Next.js app using Playwright to Vercel. Regarding the part where Japanese could not be displayed, we were able to apply Japanese fonts to the screenshot by using the package’s functions. 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.