Skip to main content
RapidDev - Software Development Agency
bolt-ai-integrationsBolt Chat + API Route

How to Integrate Bolt.new with TikTok Ads

Integrate Bolt.new with TikTok Ads using the TikTok Marketing API via Next.js API routes. Create a TikTok for Business developer app, complete the app review process, then authenticate with OAuth 2.0 to fetch campaign, ad group, and ad performance analytics. Build a TikTok Ads dashboard showing video-specific engagement metrics. TikTok's API requires advertiser account approval and app review — budget one to two weeks for access before building.

What you'll learn

  • How to create a TikTok for Business developer app and navigate the app review process
  • How to complete OAuth 2.0 authorization and manage access tokens for the TikTok Marketing API
  • How to fetch campaign and ad group performance metrics including video-specific engagement data
  • How to build a TikTok Ads dashboard highlighting short-video metrics like video view rate and average watch time
  • How to add TikTok Pixel conversion tracking to your deployed Bolt app
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate20 min read40 minutesMarketingApril 2026RapidDev Engineering Team
TL;DR

Integrate Bolt.new with TikTok Ads using the TikTok Marketing API via Next.js API routes. Create a TikTok for Business developer app, complete the app review process, then authenticate with OAuth 2.0 to fetch campaign, ad group, and ad performance analytics. Build a TikTok Ads dashboard showing video-specific engagement metrics. TikTok's API requires advertiser account approval and app review — budget one to two weeks for access before building.

Build a TikTok Ads Analytics Dashboard in Bolt.new

TikTok has become one of the most important advertising platforms for brands targeting Gen Z and Millennial audiences. With over 1 billion monthly active users spending an average of 95 minutes per day on the platform, TikTok's engagement rates consistently exceed those of any other social platform. The short-form video format creates unique advertising metrics that standard ad dashboards are not designed to show: average watch time, video completion rate at 25%, 50%, 75%, and 100% marks, and whether users clicked through after watching the full video.

The TikTok Marketing API provides complete programmatic access to your TikTok for Business advertising data. Unlike Quora's limited API availability or Reddit's separate approval process, TikTok's Marketing API is accessible to any verified TikTok for Business developer — though the app review process does require documentation of your intended use case and takes one to two weeks. The API follows REST conventions with OAuth 2.0 authentication, and outbound calls work in Bolt's WebContainer for reading analytics during development.

For Bolt developers, a TikTok Ads integration enables building dashboards that surface the video-performance metrics TikTok's native Ads Manager buries in report exports. A custom dashboard can combine TikTok creative performance with your own conversion data, compare ROAS across campaign objectives, and surface creative fatigue signals — when an ad's performance is declining because the audience has seen it too many times — before significant budget is wasted.

Integration method

Bolt Chat + API Route

Bolt generates Next.js API routes that call TikTok's Marketing API with access tokens obtained through OAuth 2.0, keeping credentials server-side. TikTok's API is REST over HTTPS, so outbound calls for campaign analytics work in Bolt's WebContainer. OAuth 2.0 authorization requires a deployed redirect URI for the initial token flow, but a stored access token enables ongoing server-side API calls without user interaction.

Prerequisites

  • A Bolt.new account with a Next.js project
  • A TikTok for Business account at business.tiktok.com with an active advertiser account
  • A TikTok developer app created at developers.tiktok.com with Marketing API access applied for
  • App review completed and Marketing API permissions approved (1-2 weeks typical)
  • The initial OAuth authorization completed to obtain an access token (requires a deployed redirect URI)

Step-by-step guide

1

Create TikTok for Business Developer App and Apply for Marketing API

TikTok's Marketing API access requires creating an app in TikTok's developer portal and applying for the Marketing API product within that app. The process has two phases: app creation (immediate) and API access approval (one to two weeks). Go to developers.tiktok.com and sign in with your TikTok for Business account. Click 'Create app' and fill in the required information: app name, description, website URL, and your intended use case. Under 'Products,' look for 'Marketing API' and click to add it. You will be prompted to describe your use case — be specific about building an analytics dashboard for your own TikTok Ads account. After submitting, TikTok's team reviews your application. The review typically takes five to ten business days. You receive an email notification when approved. While waiting, note your App ID (Client Key) and App Secret (Client Secret) from the app dashboard — you will need these for OAuth. Your TikTok Advertiser ID is different from your developer App ID. Find it in TikTok Ads Manager (ads.tiktok.com) — it is the numeric ID shown in the account selector dropdown or in the URL when viewing your account. The Advertiser ID format is a 19-digit number like `7012345678901234567`. Once API access is approved, your app is authorized to call Marketing API endpoints on behalf of TikTok for Business accounts that authorize it. Add your App ID, App Secret, and Advertiser ID to your Bolt project's .env file.

Bolt.new Prompt

Add to .env: TIKTOK_APP_ID=your-app-id, TIKTOK_APP_SECRET=your-app-secret, TIKTOK_ACCESS_TOKEN=your-access-token, TIKTOK_ADVERTISER_ID=your-advertiser-id. Create lib/tiktok.ts that exports a tiktokFetch helper. The function should call TikTok Marketing API at https://business-api.tiktok.com/open_api/v1.3/{endpoint} with Access-Token header from TIKTOK_ACCESS_TOKEN and Content-Type application/json. Handle TikTok's response envelope format where real data is in response.data and errors are in response.message when response.code !== 0.

Paste this in Bolt.new chat

lib/tiktok.ts
1// lib/tiktok.ts
2const TIKTOK_API_BASE = 'https://business-api.tiktok.com/open_api/v1.3';
3
4interface TikTokResponse<T> {
5 code: number;
6 message: string;
7 data?: T;
8 request_id?: string;
9}
10
11interface TikTokFetchOptions {
12 params?: Record<string, string>;
13 method?: 'GET' | 'POST';
14 body?: Record<string, unknown>;
15}
16
17export async function tiktokFetch<T = unknown>(
18 endpoint: string,
19 options: TikTokFetchOptions = {}
20): Promise<T> {
21 const accessToken = process.env.TIKTOK_ACCESS_TOKEN;
22 if (!accessToken) {
23 throw new Error('TIKTOK_ACCESS_TOKEN is not configured');
24 }
25
26 const url = new URL(`${TIKTOK_API_BASE}/${endpoint}`);
27 if (options.params) {
28 Object.entries(options.params).forEach(([k, v]) => url.searchParams.set(k, v));
29 }
30
31 const response = await fetch(url.toString(), {
32 method: options.method || 'GET',
33 headers: {
34 'Access-Token': accessToken,
35 'Content-Type': 'application/json',
36 },
37 body: options.body ? JSON.stringify(options.body) : undefined,
38 });
39
40 const result = await response.json() as TikTokResponse<T>;
41
42 if (result.code !== 0) {
43 throw new Error(`TikTok API error ${result.code}: ${result.message}`);
44 }
45
46 if (!result.data) {
47 throw new Error('TikTok API returned no data');
48 }
49
50 return result.data;
51}
52
53export function getTikTokAdvertiserId(): string {
54 const id = process.env.TIKTOK_ADVERTISER_ID;
55 if (!id) throw new Error('TIKTOK_ADVERTISER_ID is not configured');
56 return id;
57}

Pro tip: TikTok's Marketing API uses a custom authentication header 'Access-Token' rather than the standard 'Authorization: Bearer' header used by most REST APIs. If you get 401 errors despite having a valid token, check that you are using the 'Access-Token' header name, not 'Authorization'.

Expected result: The TikTok API helper is configured. The tiktokFetch function correctly uses the 'Access-Token' header and handles TikTok's response envelope format. A test call to /v1.3/oauth2/advertiser/get should return advertiser account details.

2

Complete OAuth Authorization and Obtain Access Token

TikTok Marketing API uses OAuth 2.0 with a standard authorization code flow. The initial authorization requires redirecting the user to TikTok's consent screen on a deployed URL, since TikTok cannot redirect back to Bolt's WebContainer preview. The authorization URL is: `https://ads.tiktok.com/marketing_api/auth?app_id={APP_ID}&state={RANDOM_STATE}&redirect_uri={ENCODED_REDIRECT_URI}&rid={RID}`. The `rid` parameter is a unique identifier for the authorization request — generate a UUID. The redirect URI must exactly match one registered in your TikTok developer app settings. After the user authorizes, TikTok redirects to your callback URL with an `auth_code` parameter. Exchange this code for an access token by calling: `POST https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/` with a JSON body containing `app_id`, `auth_code`, and `secret`. Unlike most OAuth providers, TikTok Marketing API tokens have a fixed expiry of 24 hours and do not support refresh tokens in the traditional sense. Instead, you use a 'refresh access token' endpoint with your existing access token to extend it — but this extension only works while the token is still valid. If a token expires before being refreshed, the full authorization flow must be repeated. For a single-account dashboard (your own TikTok Ads account), a practical approach is to generate a new access token daily using an automated job or generate one manually for development. TikTok's Business API documentation also describes 'Long Term Tokens' available through a separate process for apps that need persistent access — contact TikTok's business support if you need non-expiring tokens for a production dashboard. For initial setup, deploy a minimal version of your app to get the redirect URI working, complete the OAuth flow, copy the access token to your .env, and proceed with building the dashboard.

Bolt.new Prompt

Create a Next.js API route at app/api/tiktok/auth/callback/route.ts that receives auth_code from TikTok's OAuth redirect. Exchange it for an access token by POSTing to https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/ with app_id=TIKTOK_APP_ID, secret=TIKTOK_APP_SECRET, auth_code from query params. Return { accessToken, expiresIn, advertiserId, message: 'Copy TIKTOK_ACCESS_TOKEN to your .env' }. Also create /api/tiktok/auth/refresh that extends an existing valid token using the refresh endpoint.

Paste this in Bolt.new chat

app/api/tiktok/auth/callback/route.ts
1// app/api/tiktok/auth/callback/route.ts
2import { NextResponse } from 'next/server';
3
4export async function GET(request: Request) {
5 const { searchParams } = new URL(request.url);
6 const authCode = searchParams.get('auth_code');
7
8 if (!authCode) {
9 return NextResponse.json(
10 { error: 'No auth_code received from TikTok OAuth redirect' },
11 { status: 400 }
12 );
13 }
14
15 const appId = process.env.TIKTOK_APP_ID;
16 const appSecret = process.env.TIKTOK_APP_SECRET;
17
18 if (!appId || !appSecret) {
19 return NextResponse.json(
20 { error: 'TIKTOK_APP_ID or TIKTOK_APP_SECRET not configured' },
21 { status: 500 }
22 );
23 }
24
25 const response = await fetch(
26 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/',
27 {
28 method: 'POST',
29 headers: { 'Content-Type': 'application/json' },
30 body: JSON.stringify({
31 app_id: appId,
32 secret: appSecret,
33 auth_code: authCode,
34 }),
35 }
36 );
37
38 const result = await response.json() as {
39 code: number;
40 message: string;
41 data?: {
42 access_token: string;
43 advertiser_ids: string[];
44 expires_in: number;
45 };
46 };
47
48 if (result.code !== 0 || !result.data) {
49 return NextResponse.json(
50 { error: `Token exchange failed: ${result.message}` },
51 { status: 500 }
52 );
53 }
54
55 return NextResponse.json({
56 accessToken: result.data.access_token,
57 advertiserIds: result.data.advertiser_ids,
58 expiresIn: result.data.expires_in,
59 expiresAt: new Date(Date.now() + result.data.expires_in * 1000).toISOString(),
60 message: 'Add TIKTOK_ACCESS_TOKEN to your .env file. Token expires in 24 hours.',
61 envLine: `TIKTOK_ACCESS_TOKEN=${result.data.access_token}`,
62 });
63}

Pro tip: TikTok access tokens expire after 24 hours. For a production dashboard, build an automated token refresh job — call the refresh endpoint before the token expires and update the stored token. The refresh endpoint is POST /v1.3/oauth2/access_token/refresh/ with app_id, secret, and the current access_token.

Expected result: The auth callback route returns an access token after TikTok redirects with an auth_code. Copy the TIKTOK_ACCESS_TOKEN to your .env file. The token is valid for 24 hours, so subsequent API calls to the campaign endpoints will work during that window.

3

Fetch Campaign Performance Analytics

TikTok's Marketing API reports use a single reporting endpoint with a flexible dimension and metric system. Rather than separate endpoints per metric type, all performance data is requested from `GET /v1.3/report/integrated/get/` with advertiser_id, report_type, dimensions, metrics, and date range parameters. For campaign-level reporting, set `report_type=BASIC` and `dimensions=["campaign_id"]`. For ad group level, use `dimensions=["adgroup_id"]`. For ad level (individual creatives), use `dimensions=["ad_id"]`. Additional dimensions you can include: `stat_time_day` for daily breakdowns, `age`, `gender`, `country_code` for demographic breakdowns. Key metrics for a TikTok Ads dashboard: standard ad metrics — `spend`, `impressions`, `clicks`, `ctr`, `cpc`, `conversions`, `cpa`, `conversion_rate`. TikTok-specific video metrics — `video_play_actions` (total starts), `video_watched_2s`, `video_watched_6s`, `video_completion_rate` (percentage who watched the full ad), `average_video_play_per_user` (average seconds watched), `engaged_view` (3 second views). Engagement metrics — `likes`, `comments`, `shares`, `follows`, `profile_visits`. The hook rate (sometimes called 'thumb-stop rate') is calculated as `video_watched_2s / impressions` — it measures whether the opening seconds of the video stopped the scroll. A hook rate above 25% is generally considered strong; below 15% suggests the creative opening needs work. The hold rate is `video_watched_6s / video_watched_2s` — measuring retention after the initial hook. TikTok returns paginated data with a `page_info` object containing `total_page` and `page`. For most accounts, one page of 20-50 campaigns is sufficient. For agencies managing many campaigns, implement pagination. The metrics are returned in a `list` array where each item contains a `metrics` object and a `dimensions` object. Join the dimensions (campaign ID and name) with the metrics by matching on the campaign ID field.

Bolt.new Prompt

Create a Next.js API route at app/api/tiktok/campaigns/route.ts that fetches campaign reporting from TikTok Marketing API using tiktokFetch from lib/tiktok.ts. Call /v1.3/report/integrated/get/ with advertiser_id=TIKTOK_ADVERTISER_ID, report_type=BASIC, dimensions=[campaign_id], start_date and end_date from query params (default last 30 days), metrics=[spend,impressions,clicks,ctr,cpc,conversions,cpa,video_play_actions,video_watched_2s,video_watched_6s,video_completion_rate]. Calculate hook_rate (video_watched_2s/impressions*100). Return sorted by spend descending with totals.

Paste this in Bolt.new chat

app/api/tiktok/campaigns/route.ts
1// app/api/tiktok/campaigns/route.ts
2import { NextResponse } from 'next/server';
3import { tiktokFetch, getTikTokAdvertiserId } from '@/lib/tiktok';
4
5interface TikTokReportItem {
6 metrics: {
7 spend: string;
8 impressions: string;
9 clicks: string;
10 ctr: string;
11 cpc: string;
12 conversions: string;
13 cpa: string;
14 video_play_actions: string;
15 video_watched_2s: string;
16 video_watched_6s: string;
17 video_completion_rate: string;
18 };
19 dimensions: {
20 campaign_id: string;
21 campaign_name?: string;
22 };
23}
24
25interface TikTokReportResponse {
26 list: TikTokReportItem[];
27 page_info: {
28 total_number: number;
29 page: number;
30 page_size: number;
31 total_page: number;
32 };
33}
34
35export async function GET(request: Request) {
36 const { searchParams } = new URL(request.url);
37 const advertiserId = getTikTokAdvertiserId();
38
39 const endDate = searchParams.get('endDate') || new Date().toISOString().split('T')[0];
40 const startDate = searchParams.get('startDate') ||
41 new Date(Date.now() - 30 * 86400000).toISOString().split('T')[0];
42
43 try {
44 const reportData = await tiktokFetch<TikTokReportResponse>(
45 'report/integrated/get/',
46 {
47 params: {
48 advertiser_id: advertiserId,
49 report_type: 'BASIC',
50 dimensions: JSON.stringify(['campaign_id']),
51 metrics: JSON.stringify([
52 'spend', 'impressions', 'clicks', 'ctr', 'cpc',
53 'conversions', 'cpa', 'video_play_actions',
54 'video_watched_2s', 'video_watched_6s', 'video_completion_rate',
55 ]),
56 start_date: startDate,
57 end_date: endDate,
58 page_size: '50',
59 page: '1',
60 },
61 }
62 );
63
64 const campaigns = (reportData.list || []).map((item) => {
65 const m = item.metrics;
66 const impressions = parseInt(m.impressions || '0', 10);
67 const watched2s = parseInt(m.video_watched_2s || '0', 10);
68
69 return {
70 id: item.dimensions.campaign_id,
71 name: item.dimensions.campaign_name || item.dimensions.campaign_id,
72 spend: parseFloat(m.spend || '0'),
73 impressions,
74 clicks: parseInt(m.clicks || '0', 10),
75 ctr: parseFloat(m.ctr || '0'),
76 cpc: parseFloat(m.cpc || '0'),
77 conversions: parseInt(m.conversions || '0', 10),
78 cpa: parseFloat(m.cpa || '0'),
79 videoStarts: parseInt(m.video_play_actions || '0', 10),
80 watched2s,
81 watched6s: parseInt(m.video_watched_6s || '0', 10),
82 completionRate: parseFloat(m.video_completion_rate || '0'),
83 hookRate: impressions > 0 ? (watched2s / impressions) * 100 : 0,
84 };
85 });
86
87 campaigns.sort((a, b) => b.spend - a.spend);
88
89 const totals = campaigns.reduce(
90 (acc, c) => ({
91 spend: acc.spend + c.spend,
92 impressions: acc.impressions + c.impressions,
93 clicks: acc.clicks + c.clicks,
94 conversions: acc.conversions + c.conversions,
95 }),
96 { spend: 0, impressions: 0, clicks: 0, conversions: 0 }
97 );
98
99 return NextResponse.json({ campaigns, totals, dateRange: { startDate, endDate } });
100 } catch (err) {
101 const message = err instanceof Error ? err.message : 'Failed to fetch TikTok campaigns';
102 return NextResponse.json({ error: message }, { status: 500 });
103 }
104}

Pro tip: TikTok returns all metric values as strings, not numbers — '1234' not 1234, and '12.34' not 12.34. Always parse metrics with parseInt or parseFloat before using them in calculations or displaying in the dashboard. Missing metrics are returned as '--' not null, so handle both empty string and '--' in your parsing.

Expected result: The campaigns route returns TikTok campaign performance data with parsed numeric values and calculated hook rate. Call /api/tiktok/campaigns in the browser to verify real campaign data with video metrics appears correctly.

4

Build the TikTok Ads Analytics Dashboard

TikTok Ads dashboards should surface video-specific engagement metrics that differentiate TikTok's performance model from other ad platforms. The most valuable TikTok-specific metrics are Hook Rate (percentage of impressions that resulted in at least 2 seconds of watch time, measuring opening effectiveness), Hold Rate (percentage who continued watching after the initial hook), Video Completion Rate (percentage who watched the full ad), and Average Watch Time. Organize the dashboard with this hierarchy: a summary header with total spend, total impressions, total conversions, and average hook rate; a video performance section showing the distribution of completion rates across campaigns; and a campaign table with both standard and TikTok-specific columns. For the campaign table, consider two tab views: 'Performance' (spend, impressions, clicks, CTR, conversions, CPA) and 'Creative' (video starts, hook rate, completion rate, watched 6s). This lets users switch between business outcome metrics and creative quality signals without overwhelming a single table with too many columns. Benchmarks to show in the dashboard: TikTok's industry average hook rate is 25-40% for well-optimized creatives; hold rate above 50% indicates strong content retention; video completion rate above 20% for in-feed ads is considered strong. Display these benchmarks as reference lines or annotations in your charts so users can immediately contextualize their performance. For the color-coded column indicators: hook rate above 30% = green, 15-30% = yellow, below 15% = red. CPA below account average = green, 1-2x average = yellow, above 2x = red. These visual signals help users immediately identify which campaigns need creative attention without manual comparison.

Bolt.new Prompt

Build a TikTok Ads dashboard page at /tiktok-ads that fetches from /api/tiktok/campaigns with Last 7d / Last 30d date presets. Show: (1) summary cards for total spend, total impressions, total conversions, and average hook rate; (2) a Recharts bar chart of spend by campaign; (3) a campaign table with two tabs — 'Performance' tab: Name, Spend, Impressions, Clicks, CTR, Conversions, CPA; 'Creative' tab: Name, Video Starts, Hook Rate (color-coded), Completion Rate, Watched 6s. Include a TikTok industry benchmark note below the creative tab (Hook Rate benchmark: >25%). Add loading skeletons and error state.

Paste this in Bolt.new chat

Pro tip: TikTok's CTR metric is reported as a percentage number (e.g., 2.34 for 2.34%), not a decimal fraction like some other platforms. Display it with a '%' suffix without multiplying by 100. Completion rate is also returned as a percentage number, not a decimal.

Expected result: The TikTok Ads dashboard renders with campaign data, video metrics on the Creative tab, and color-coded hook rate indicators. The date range presets reload data correctly and the benchmark note provides context for creative performance.

5

Deploy and Add TikTok Pixel for Conversion Tracking

Outbound TikTok API calls work in Bolt's WebContainer preview for reading campaign analytics. The TikTok Pixel (for browser-side conversion tracking) and the OAuth redirect callback require deployment to a live HTTPS domain. Deploy to Netlify via Settings → Applications → Connect Netlify, or click Publish to deploy to Bolt Cloud. Add server-side environment variables: `TIKTOK_APP_ID`, `TIKTOK_APP_SECRET`, `TIKTOK_ACCESS_TOKEN`, and `TIKTOK_ADVERTISER_ID`. Add the client-side `NEXT_PUBLIC_TIKTOK_PIXEL_ID` for browser-side conversion tracking. The TikTok Pixel enables conversion tracking and powers TikTok's algorithm optimization. Without it, TikTok cannot optimize campaigns toward conversion events and ROAS data is unavailable. Install it by creating a `TikTokPixel` component using Next.js Script that loads TikTok's pixel JavaScript from `https://analytics.tiktok.com/i18n/pixel/events.js`, initializes with your Pixel ID, and fires a PageView event. Add the component to your root layout. For conversion events, use `ttq.track('CompletePayment', { content_id, content_type, currency, value })` for purchases and `ttq.track('SubmitForm')` for lead generation. TikTok also supports server-side events via the Events API at `https://business-api.tiktok.com/open_api/v1.3/pixel/track/` — the same access token used for Marketing API calls works for the Events API, making TikTok's server-side tracking easier to set up than platforms requiring separate API tokens. For the TikTok Pixel access token, note that it is different from the Marketing API access token. The Pixel token is specific to your pixel and is found in TikTok Ads Manager → Assets → Events → your pixel → Settings → Access token. The Marketing API access token (from OAuth) is used for campaign analytics calls.

Bolt.new Prompt

Create a components/TikTokPixel.tsx component that loads TikTok Pixel script using Next.js Script with NEXT_PUBLIC_TIKTOK_PIXEL_ID. Initialize ttq and fire a ViewContent event. Create a hooks/useTikTokTrack.ts hook that wraps ttq.track() with TypeScript types for CompletePayment (with value, currency, content_id), SubmitForm, and ViewContent events. Add the pixel component to root layout.tsx.

Paste this in Bolt.new chat

components/TikTokPixel.tsx
1// components/TikTokPixel.tsx
2'use client';
3
4import Script from 'next/script';
5
6declare global {
7 interface Window {
8 ttq?: {
9 track: (event: string, params?: Record<string, unknown>) => void;
10 page: () => void;
11 identify: (params: Record<string, unknown>) => void;
12 load: (pixelId: string) => void;
13 };
14 }
15}
16
17export function TikTokPixel() {
18 const pixelId = process.env.NEXT_PUBLIC_TIKTOK_PIXEL_ID;
19 if (!pixelId) return null;
20
21 return (
22 <Script
23 id="tiktok-pixel"
24 strategy="afterInteractive"
25 dangerouslySetInnerHTML={{
26 __html: `
27 !function (w, d, t) {
28 w.TiktokAnalyticsObject=t;
29 var ttq=w[t]=w[t]||[];
30 ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"];
31 ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};
32 for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);
33 ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e};
34 ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";
35 ttq._i=ttq._i||{};
36 ttq._i[e]=[];
37 ttq._i[e]._u=i;
38 ttq._t=ttq._t||{};
39 ttq._t[e]=+new Date;
40 ttq._o=ttq._o||{};
41 ttq._o[e]=n||{};
42 var o=document.createElement("script");
43 o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;
44 var a=document.getElementsByTagName("script")[0];
45 a.parentNode.insertBefore(o,a)};
46 ttq.load('${pixelId}');
47 ttq.page();
48 }(window, document, 'ttq');
49 `,
50 }}
51 />
52 );
53}

Pro tip: TikTok Ads Manager provides a 'Pixel Check' tool under Assets → Events → your pixel → Test Events. Use it to verify conversion events are firing correctly after deployment. The test tool shows real-time events from your browser session, making it easy to confirm the pixel is working without waiting for aggregated reporting.

Expected result: After deploying, the TikTok Pixel fires ViewContent on every page load. Purchase events trigger CompletePayment tracking calls. Conversion data begins appearing in TikTok Ads Manager → Assets → Events within a few hours of the first tracked events.

Common use cases

TikTok Ads Campaign Performance Dashboard

Build a comprehensive campaign performance dashboard showing spend, impressions, clicks, conversions, and TikTok-specific video metrics. Display campaigns by objective — awareness, traffic, app installs, conversions — with the relevant primary KPI highlighted for each. Include a spend pacing indicator showing budget utilization rate.

Bolt.new Prompt

Build a TikTok Ads analytics dashboard. Create a Next.js API route at /api/tiktok/campaigns that calls TikTok Marketing API v1.3 to fetch campaigns and their performance stats (spend, impressions, clicks, cpc, ctr, conversions, video_play_actions, video_watched_2s, video_watched_6s) for a date range. Use TIKTOK_ACCESS_TOKEN, TIKTOK_ADVERTISER_ID from process.env. Build a React dashboard with summary cards (total spend, total impressions, total conversions, average video view rate) and a sortable campaign table with status badges. Add Last 7d / Last 30d date presets.

Copy this prompt to try it in Bolt.new

TikTok Creative Performance Analyzer

Analyze video creative performance at the ad level to identify which TikTok videos are driving results and which are experiencing audience fatigue. Compare video completion rates, average watch time, and conversion rate across ad variants to inform your next creative sprint.

Bolt.new Prompt

Create a TikTok creative analyzer. Build a Next.js API route at /api/tiktok/ads that fetches all active ads with video performance metrics: impressions, video_play_actions (starts), video_watched_2s, video_watched_6s, video_completion_rate, clicks, conversions, spend, cpa. Calculate video hook rate (video_watched_2s / impressions) and hold rate (video_watched_6s / video_play_actions). Build a React grid showing each ad with hook rate, hold rate, completion rate, and CPA. Flag ads with hook rate below 25% or completion rate below 30% as needing creative refresh. Use TIKTOK_ACCESS_TOKEN and TIKTOK_ADVERTISER_ID from process.env.

Copy this prompt to try it in Bolt.new

TikTok Audience Targeting Performance Tracker

Track which audience segments, demographics, and placements are driving the best performance on TikTok. Analyze age group, gender, and geographic performance data to identify your highest-converting audience segments and reallocate budget toward the most efficient targeting configurations.

Bolt.new Prompt

Build a TikTok audience analytics page. Create a Next.js API route at /api/tiktok/audience that calls TikTok Reporting API with dimensions [age, gender] and metrics [spend, impressions, clicks, conversions, cpa] for the last 30 days. Use TIKTOK_ACCESS_TOKEN and TIKTOK_ADVERTISER_ID from process.env. Build a React dashboard with a demographic breakdown table showing performance by age group (13-17, 18-24, 25-34, 35-44, 45+) and gender. Highlight age groups with CPA below the account average. Include a geographic map component showing top 10 countries by conversion volume.

Copy this prompt to try it in Bolt.new

Troubleshooting

TikTok API returns error code 40001 'Invalid Access Token'

Cause: TikTok access tokens expire after 24 hours. If the TIKTOK_ACCESS_TOKEN in .env is older than 24 hours, all API calls return this error.

Solution: Generate a new access token by completing the OAuth authorization flow again or calling the token refresh endpoint. For production, build an automated token refresh that calls /v1.3/oauth2/access_token/refresh/ before the current token expires. Store the token in a database with its expiry time rather than just in .env for production multi-token management.

typescript
1// Token refresh endpoint:
2const refreshResponse = await fetch(
3 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/refresh/',
4 {
5 method: 'POST',
6 headers: { 'Content-Type': 'application/json' },
7 body: JSON.stringify({
8 app_id: process.env.TIKTOK_APP_ID,
9 secret: process.env.TIKTOK_APP_SECRET,
10 access_token: process.env.TIKTOK_ACCESS_TOKEN,
11 }),
12 }
13);
14const refreshData = await refreshResponse.json();

Report endpoint returns error 40002 'No permission' or empty data

Cause: The access token was granted by an account that does not have access to the advertiser ID specified in TIKTOK_ADVERTISER_ID, or the Marketing API permissions were not approved for the app during review.

Solution: Verify the advertiser ID matches the account that authorized the app during OAuth. Call /v1.3/oauth2/advertiser/get/ to list all advertiser IDs accessible with your current token. If your intended advertiser ID is not in the list, the authorizing user does not have access to that account.

typescript
1// List accessible advertiser IDs:
2const advertisers = await tiktokFetch('oauth2/advertiser/get/', {
3 params: {
4 app_id: process.env.TIKTOK_APP_ID || '',
5 secret: process.env.TIKTOK_APP_SECRET || '',
6 access_token: process.env.TIKTOK_ACCESS_TOKEN || '',
7 },
8});
9console.log('Accessible advertisers:', advertisers);

Metric values are returning as '--' strings instead of numbers

Cause: TikTok returns '--' for metrics with no data in the requested date range (e.g., video metrics for non-video campaigns, or conversion metrics for campaigns with no pixel tracking).

Solution: Replace '--' values with 0 or null in your parsing logic. For video metrics on campaigns with no video spend, '--' is expected and should be treated as 0. For conversion metrics on campaigns without pixel tracking, '--' should display as 'N/A' rather than 0 to avoid misleading users.

typescript
1// Handle '--' in metric parsing:
2function parseTikTokMetric(value: string | undefined, defaultValue = 0): number {
3 if (!value || value === '--' || value === '') return defaultValue;
4 const parsed = parseFloat(value);
5 return isNaN(parsed) ? defaultValue : parsed;
6}

OAuth callback URL mismatch — TikTok rejects the auth_code exchange

Cause: During development in Bolt's WebContainer, the dynamic preview URL cannot be registered as an OAuth redirect URI. TikTok rejects authorization codes when the redirect_uri does not exactly match the registered URI.

Solution: Deploy to Netlify or Bolt Cloud to get a stable URL, register it in your TikTok developer app settings as the redirect URI, then complete the OAuth authorization flow on the deployed site. After getting the access token, copy it to your .env for ongoing development.

Best practices

  • Build automated TikTok access token refresh since tokens expire every 24 hours — store the token expiry timestamp alongside the token and proactively refresh when less than one hour remains, rather than waiting for API errors.
  • Use the 'Access-Token' request header name rather than 'Authorization: Bearer' — TikTok Marketing API uses a non-standard header name that causes 401 errors if the standard OAuth header format is used instead.
  • Surface hook rate (video_watched_2s / impressions * 100) and completion rate as primary creative metrics alongside standard CTR — these video-specific signals are TikTok's most actionable performance indicators and are not available on other ad platforms.
  • Parse all TikTok metric values with parseFloat or parseInt since the API returns all metrics as strings, and treat '--' values as 0 or N/A depending on the metric type.
  • Cache TikTok API responses for up to 15 minutes since campaign analytics data updates at most hourly, and the 24-hour token expiry means you need to be conservative with API calls to avoid hitting rate limits during the token's lifetime.
  • Add the TikTok Pixel to your deployed app for conversion tracking — without it, TikTok cannot optimize toward conversions and ROAS data is unavailable in campaign analytics.
  • Use TikTok's reporting dimensions system (dimensions=['campaign_id', 'stat_time_day']) rather than multiple API calls to get daily breakdowns — the integrated reporting endpoint handles all dimensions in a single request.
  • Store all credentials as server-side environment variables without NEXT_PUBLIC_ prefix — access tokens, App ID, and App Secret must stay server-side to prevent unauthorized API access from client-side code.

Alternatives

Frequently asked questions

Does Bolt.new have a native TikTok Ads integration?

No — Bolt.new does not have a native TikTok Ads connector. The integration requires building Next.js API routes that call TikTok's Marketing API with OAuth 2.0 access tokens. Bolt's AI can generate this code from a descriptive prompt, but note that TikTok's custom 'Access-Token' header and all-string metric values require specific handling that differs from other ad platform APIs.

Can I test the TikTok Ads dashboard in Bolt's WebContainer without deploying?

Yes, once you have an access token — outbound calls to TikTok's Marketing API work in the WebContainer. The challenge is obtaining the initial access token, since TikTok's OAuth redirect cannot reach the WebContainer's dynamic URLs. Deploy a minimal version first to complete the OAuth flow and get the token, then add the token to .env and continue development in the preview with real data.

Why do TikTok access tokens expire so quickly (24 hours)?

TikTok Marketing API access tokens have a 24-hour lifetime by design as a security measure. You can extend a valid token using the refresh endpoint before it expires. TikTok also offers 'Long Term Tokens' for enterprise API partners who need non-expiring tokens — contact TikTok's business API support if you need permanent tokens for a production dashboard.

What is hook rate and why does it matter for TikTok Ads?

Hook rate measures what percentage of users who saw your ad watched at least the first 2 seconds. On TikTok's infinite-scroll feed, users decide within the first second whether to keep watching or scroll past. A high hook rate (above 25%) means your creative's opening grabs attention effectively. Hook rate is the single most important creative quality signal on TikTok and directly correlates with video completion rate, click-through rate, and ultimately conversion performance.

How do TikTok's video completion metrics work?

TikTok tracks four video completion checkpoints: 25% (video_watched_25p), 50%, 75%, and 100% (video_completion_rate). The video_completion_rate metric is the percentage of impressions where the full video was watched. TikTok also provides video_watched_2s and video_watched_6s as absolute counts of users who reached those timestamps. Together these create a completion funnel that shows where viewers drop off — typically the sharpest drop is between the 2-second mark and the 6-second mark.

Do I need a separate TikTok Pixel token for conversion tracking?

Yes — the TikTok Pixel has its own access token separate from the Marketing API OAuth token. Find the Pixel access token in TikTok Ads Manager under Assets → Events → your pixel → Settings → Access Token. This token is used for server-side Events API calls. The client-side Pixel JavaScript only needs the Pixel ID (NEXT_PUBLIC_TIKTOK_PIXEL_ID) to fire browser events — no token is required for client-side tracking.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.