* Server a response with an API token obtained from the query params.
(
scopePath: string,
request: NextRequest,
serve: (apiToken: string) => Promise<NextResponse>
)
| 452 | * Server a response with an API token obtained from the query params. |
| 453 | */ |
| 454 | async function serveWithQueryAPIToken( |
| 455 | scopePath: string, |
| 456 | request: NextRequest, |
| 457 | serve: (apiToken: string) => Promise<NextResponse> |
| 458 | ) { |
| 459 | // We store the API token in a cookie that is scoped to the specific route |
| 460 | // to avoid errors when multiple previews are opened in different tabs. |
| 461 | const cookieName = getPathScopedCookieName('gitbook-api-token', scopePath); |
| 462 | |
| 463 | // Extract a potential GitBook API token passed in the request |
| 464 | // If found, we redirect to the same URL but with the token in the cookie |
| 465 | const queryAPIToken = request.nextUrl.searchParams.get('token'); |
| 466 | if (queryAPIToken) { |
| 467 | request.nextUrl.searchParams.delete('token'); |
| 468 | return writeResponseCookies(NextResponse.redirect(request.nextUrl.toString()), [ |
| 469 | { |
| 470 | name: cookieName, |
| 471 | value: queryAPIToken, |
| 472 | options: { |
| 473 | httpOnly: true, |
| 474 | sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined, |
| 475 | secure: process.env.NODE_ENV === 'production', |
| 476 | maxAge: 60 * 60, // 1 hour |
| 477 | }, |
| 478 | }, |
| 479 | ]); |
| 480 | } |
| 481 | |
| 482 | const apiToken = request.cookies.get(cookieName)?.value; |
| 483 | if (!apiToken) { |
| 484 | throw new DataFetcherError('Missing API token', 400); |
| 485 | } |
| 486 | |
| 487 | return serve(apiToken); |
| 488 | } |
| 489 | |
| 490 | /** |
| 491 | * The URL of the GitBook content can be passed in 3 different ways (in order of priority): |
no test coverage detected