Skip to content

Commit

Permalink
feat: use single browser instance
Browse files Browse the repository at this point in the history
  • Loading branch information
junseublim committed Dec 30, 2024
1 parent 1b3cc23 commit 8ccc204
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/app/board/api/screenshot/route.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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',
Expand All @@ -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,
Expand All @@ -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')
Expand All @@ -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()
}
}
}

0 comments on commit 8ccc204

Please sign in to comment.