Skip to content

Disable any tracking when using a preview URL. #3354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/gitbook-v2/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
url: siteRequestURL,
});

const withAPIToken = async (apiToken: string | null) => {
const withAPIToken = async (apiToken: string | null, headers?: { [key: string]: string }) => {
const siteURLData = await throwIfDataError(
lookupPublishedContentByUrl({
url: siteRequestURL.toString(),
Expand Down Expand Up @@ -265,6 +265,10 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
},
});

Object.entries(headers ?? {}).forEach(([key, value]) => {
response.headers.set(key, value);
});

// Add Content Security Policy header
response.headers.set('content-security-policy', getContentSecurityPolicy());
// Basic security headers
Expand All @@ -284,7 +288,11 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
// We scope the API token to the site ID.
`${siteRequestURL.hostname}/${requestURL.pathname.slice(1).split('/')[0]}`,
request,
withAPIToken
(apiToken) =>
// Do not track page views for preview requests
withAPIToken(apiToken, {
'x-gitbook-track-page-views': '0',
})
);
}

Expand Down
17 changes: 11 additions & 6 deletions packages/gitbook/src/lib/tracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@ import { headers } from 'next/headers';
export async function shouldTrackEvents(): Promise<boolean> {
const headersList = await headers();

if (
process.env.NODE_ENV === 'development' ||
(process.env.GITBOOK_BLOCK_PAGE_VIEWS_TRACKING &&
!headersList.has('x-gitbook-track-page-views'))
) {
// No tracking in development mode
if (process.env.NODE_ENV === 'development') {
return false;
}

return true;
const headerValue = headersList.get('x-gitbook-track-page-views');

// No tracking if environment variable is set and header does not override it.
if (process.env.GITBOOK_BLOCK_PAGE_VIEWS_TRACKING && headerValue !== null) {
return false;
}

// Passing a 0 will disable tracking
return headerValue !== '0';
}