From 8ccc204e8010e2c579ea4b1d451fb6e6c617ac86 Mon Sep 17 00:00:00 2001 From: junseublim Date: Mon, 30 Dec 2024 18:50:55 +0900 Subject: [PATCH] feat: use single browser instance --- src/app/board/api/screenshot/route.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/app/board/api/screenshot/route.ts b/src/app/board/api/screenshot/route.ts index e28c1e9..d0d3931 100644 --- a/src/app/board/api/screenshot/route.ts +++ b/src/app/board/api/screenshot/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from 'next/server' -import puppeteer, { Browser } from 'puppeteer' +import puppeteer, { Browser, Page } from 'puppeteer' import { StickerStyle } from '@/types' import { createPolaroidSearchParams, @@ -12,8 +12,10 @@ type RequestBodyType = { stickers: StickerStyle[] } +let browser: Browser | null = null + const initializeBrowser = async () => { - const browser = await puppeteer.launch({ + browser = await puppeteer.launch({ args: [ '--no-sandbox', '--disable-setuid-sandbox', @@ -24,17 +26,23 @@ const initializeBrowser = async () => { ], defaultViewport: null, }) - const page = await browser.newPage() +} + +const openPage = async () => { + if (browser === null) { + await initializeBrowser() + } + + const page = await browser!.newPage() await page.setViewport({ width: 1080, height: 1920, }) - return { browser, page } + return page } export async function POST(request: Request) { - let browser: Browser | null = null - + let page: Page | null = null try { const { boardId, @@ -48,9 +56,7 @@ export async function POST(request: Request) { boardId, )}/screenshot?${polaroidParams}&${stickerParams}` - const { browser: initializedBrowser, page } = await initializeBrowser() - browser = initializedBrowser - + page = await openPage() await page.goto(url, { waitUntil: 'networkidle2' }) const element = await page.$('div#screenshot_target') @@ -71,7 +77,7 @@ export async function POST(request: Request) { return new NextResponse('Error taking screenshot', { status: 500 }) } finally { if (browser) { - await browser.close() + await page?.close() } } }