MCPcopy
hub / github.com/GitbookIO/gitbook / withAPIToken

Function withAPIToken

packages/gitbook/src/middleware.ts:175–396  ·  view source on GitHub ↗
(apiToken: string | null)

Source from the content-addressed store, hash-verified

173 request.headers.delete('x-gitbook-disable-tracking');
174
175 const withAPIToken = async (apiToken: string | null) => {
176 const siteURLData = await throwIfDataError(
177 lookupPublishedContentByUrl({
178 url: siteRequestURL.toString(),
179 visitorPayload: {
180 jwtToken: visitorToken?.token ?? undefined,
181 unsignedClaims,
182 },
183 // When the visitor auth token is pulled from the cookie, set redirectOnError when calling resolvePublishedContentByUrl to allow
184 // redirecting when the token is invalid as we could be dealing with stale token stored in the cookie.
185 // For example when the VA backend signature has changed but the token stored in the cookie is not yet expired.
186 redirectOnError: visitorToken?.source === 'visitor-auth-cookie',
187
188 // Use the API token passed in the request, if any
189 // as it could be used for .preview hostnames
190 apiToken,
191 })
192 );
193
194 const cookies: ResponseCookies = visitorParamsCookie
195 ? [
196 // If visitor.* params were passed to the site URL, include a session cookie to persist these params across navigation.
197 visitorParamsCookie,
198 ]
199 : [];
200
201 //
202 // Handle redirects
203 //
204 if ('redirect' in siteURLData) {
205 // biome-ignore lint/suspicious/noConsole: we want to log the redirect
206 console.log('redirect', siteURLData.redirect);
207 if (siteURLData.target === 'content') {
208 let contentRedirect = new URL(siteURLData.redirect, request.url);
209
210 // For content redirects, we redirect using the /url/:url format
211 // during development and testing in 'url' mode.
212 if (mode === 'url') {
213 const urlObject = new URL(siteURLData.redirect);
214 contentRedirect = new URL(
215 `/url/${urlObject.host}${urlObject.pathname}${urlObject.search}`,
216 request.url
217 );
218 }
219
220 // Keep the same search params as the original request
221 // as it might contain a VA token
222 contentRedirect.search = request.nextUrl.search;
223
224 return NextResponse.redirect(contentRedirect);
225 }
226
227 return NextResponse.redirect(siteURLData.redirect);
228 }
229
230 cookies.push(
231 ...getResponseCookiesForVisitorAuth(
232 getVisitorAuthBasePath(siteRequestURL, siteURLData),

Callers 1

serveSiteRoutesFunction · 0.85

Calls 12

throwIfDataErrorFunction · 0.90
getVisitorAuthBasePathFunction · 0.90
normalizeVisitorURLFunction · 0.90
getContentSecurityPolicyFunction · 0.90
writeResponseCookiesFunction · 0.85
encodePathInSiteContentFunction · 0.85
toStringMethod · 0.80
setMethod · 0.80
getMethod · 0.80

Tested by

no test coverage detected