To integrate Lovable with TikTok Ads, create a Supabase Edge Function that proxies TikTok Marketing API calls using a long-term access token stored in Cloud → Secrets. The Edge Function handles campaign management, ad group creation, and performance reporting. Use Lovable's chat to build TikTok ad dashboards covering Spark Ads, In-Feed Ads, and campaign analytics.
Build TikTok ad campaign management and analytics dashboards in Lovable
TikTok's Marketing API provides programmatic access to the full advertising stack: create and manage advertising accounts, build campaigns with budgets and objectives, configure ad groups with targeting parameters, upload creatives, and retrieve performance reports. The API uses a REST architecture with JSON payloads and a long-term access token for authentication — unlike many ad platforms, TikTok's Marketing API does not use short-lived tokens that require regular refresh for server-to-server access.
The TikTok advertising model is structured in three layers: campaigns (which set the objective and overall budget), ad groups (which define targeting, placement, and bid strategy), and ads (the actual creative content). Understanding this hierarchy is important for both using the API correctly and designing the dashboard UI — each layer has its own set of configuration options and performance metrics.
TikTok Ads are meaningfully different from Facebook/Meta Ads in the creative approach. Meta advertising relies on image and text ads optimized through demographic targeting. TikTok advertising is video-first and thrives on creative that blends in with organic TikTok content — particularly Spark Ads, which boost existing organic TikTok posts rather than creating purpose-built ad content. This creative-native approach means TikTok ad performance is heavily influenced by creative quality, and dashboards built in Lovable should surface creative-level metrics (video views, video completion rate, click-through rate) alongside campaign-level spend data.
Integration method
TikTok's Marketing API uses a long-term access token obtained through a Business Center OAuth flow. Because this token authorizes advertising spend, it must never appear in browser code. All TikTok Marketing API calls — campaign management, ad group operations, creative uploads, and reporting — are proxied through a Supabase Edge Function using credentials stored in Cloud → Secrets.
Prerequisites
- A Lovable account with a project that has Lovable Cloud enabled
- A TikTok Business Center account — register at business.tiktok.com
- A TikTok Ads Manager advertiser account with active campaigns or a test account
- TikTok Marketing API access approved — apply through the TikTok developer portal at developers.tiktok.com/products/marketing-api
- A long-term access token for your advertiser account and your advertiser ID
Step-by-step guide
Set up TikTok Business Center and obtain Marketing API credentials
Set up TikTok Business Center and obtain Marketing API credentials
TikTok Marketing API access requires a Business Center account and approval from TikTok's developer program. Start by navigating to business.tiktok.com and signing in with your TikTok account. If you do not have a Business Center, create one by clicking 'Create a Business Center'. Next, go to developers.tiktok.com and click 'Apply for API access'. Select 'Marketing API' from the product list. Fill in your application details including your business use case, estimated API call volume, and the advertiser accounts you want to access. TikTok reviews these applications — approval typically takes 3-7 business days. Once approved, you will receive an App ID (sometimes called client_key) and an App Secret from the TikTok developer portal. To generate a long-term access token for a specific advertiser account, you use the OAuth2 authorization flow or the sandbox environment for testing. Go to your TikTok app's dashboard in the developer portal and look for the 'Authorization' section. The long-term access token from the authorization flow is valid for a configurable period (up to one year) and is what you will store in Cloud → Secrets. You also need your advertiser account ID — a numeric string visible in TikTok Ads Manager's URL or in the account settings. Every Marketing API call requires this ID to scope requests to the correct advertiser account.
Pro tip: TikTok offers a Marketing API sandbox environment for testing without spending real ad budget. Use sandbox credentials during development and switch to production credentials only when your dashboard is ready for live data.
Expected result: You have a TikTok App ID, App Secret, a long-term access token, and your advertiser account ID. These four values are ready to store in Cloud → Secrets.
Store TikTok credentials in Cloud → Secrets
Store TikTok credentials in Cloud → Secrets
Open your Lovable project and click the '+' icon next to the Preview label to open the Cloud panel. Navigate to the Secrets tab and click 'Add new secret'. Add the following secrets: - Name: TIKTOK_ACCESS_TOKEN — Value: your long-term access token from the TikTok developer portal - Name: TIKTOK_APP_ID — Value: your TikTok application App ID - Name: TIKTOK_APP_SECRET — Value: your TikTok application App Secret - Name: TIKTOK_ADVERTISER_ID — Value: your numeric advertiser account ID The TIKTOK_ACCESS_TOKEN is the most sensitive credential — it authorizes all advertising operations including creating campaigns and accessing spend data. Store it with the same care you would an API key that directly controls real money. The TIKTOK_ADVERTISER_ID is included as a secret because it scopes all API calls to your specific advertiser account. While the advertiser ID is not a secret in the traditional sense, keeping it in Secrets means you can change it without modifying your Edge Function code — useful when managing multiple advertiser accounts or switching between sandbox and production. Lovable's security system actively blocks approximately 1,200 hardcoded API keys per day. However, for advertising API credentials that control ad spend, always use Cloud → Secrets regardless of platform-level protections.
Expected result: TIKTOK_ACCESS_TOKEN, TIKTOK_APP_ID, TIKTOK_APP_SECRET, and TIKTOK_ADVERTISER_ID appear in Cloud → Secrets with masked values.
Create the TikTok Marketing API proxy Edge Function
Create the TikTok Marketing API proxy Edge Function
Create a Supabase Edge Function that proxies requests to TikTok's Marketing API. TikTok's Marketing API base URL is https://business-api.tiktok.com/open_api/v1.3/ and all requests include the access token in the Access-Token header along with the advertiser_id as a parameter. The Edge Function routes requests based on an 'action' parameter in the POST body: 'campaigns' fetches the campaign list, 'ad_groups' fetches ad groups for a campaign, 'ads' fetches ads for an ad group, and 'report' fetches integrated reporting data. The report action is the most powerful — it supports flexible dimension and metric selection for custom analytics. Paste the prompt below into Lovable's chat to generate and deploy the function.
Create a Supabase Edge Function at supabase/functions/tiktok-ads/index.ts. Accept POST requests with a JSON body containing 'action' (campaigns | ad_groups | ads | report | update_campaign). Use TIKTOK_ACCESS_TOKEN as the Access-Token header and TIKTOK_ADVERTISER_ID in query params for all requests to https://business-api.tiktok.com/open_api/v1.3/. For 'campaigns': GET /campaign/get/. For 'report': POST /report/integrated/get/ with the provided metrics and dimensions in the body. For 'update_campaign': POST /campaign/update/ with the campaign_id and updates. Include CORS headers.
Paste this in Lovable chat
1// supabase/functions/tiktok-ads/index.ts2const TIKTOK_API_BASE = 'https://business-api.tiktok.com/open_api/v1.3';34Deno.serve(async (req) => {5 if (req.method === 'OPTIONS') {6 return new Response(null, {7 headers: {8 'Access-Control-Allow-Origin': '*',9 'Access-Control-Allow-Methods': 'POST, OPTIONS',10 'Access-Control-Allow-Headers': 'Content-Type, Authorization',11 },12 });13 }1415 const accessToken = Deno.env.get('TIKTOK_ACCESS_TOKEN');16 const advertiserId = Deno.env.get('TIKTOK_ADVERTISER_ID');1718 if (!accessToken || !advertiserId) {19 return new Response(JSON.stringify({ error: 'TikTok credentials not configured' }), {20 status: 500,21 headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },22 });23 }2425 const { action, params } = await req.json();26 const headers = {27 'Access-Token': accessToken,28 'Content-Type': 'application/json',29 };3031 let apiUrl: string;32 let fetchOptions: RequestInit;3334 if (action === 'campaigns') {35 apiUrl = `${TIKTOK_API_BASE}/campaign/get/?advertiser_id=${advertiserId}&page_size=100`;36 fetchOptions = { method: 'GET', headers };37 } else if (action === 'ad_groups') {38 apiUrl = `${TIKTOK_API_BASE}/adgroup/get/?advertiser_id=${advertiserId}&campaign_id=${params.campaign_id}`;39 fetchOptions = { method: 'GET', headers };40 } else if (action === 'report') {41 const reportBody = {42 advertiser_id: advertiserId,43 report_type: params.report_type || 'BASIC',44 dimensions: params.dimensions || ['campaign_id', 'stat_time_day'],45 metrics: params.metrics || ['spend', 'impressions', 'clicks', 'ctr', 'cpc'],46 start_date: params.start_date,47 end_date: params.end_date,48 page_size: 100,49 };50 apiUrl = `${TIKTOK_API_BASE}/report/integrated/get/`;51 fetchOptions = { method: 'POST', headers, body: JSON.stringify(reportBody) };52 } else if (action === 'update_campaign') {53 const updateBody = { advertiser_id: advertiserId, campaign_id: params.campaign_id, ...params.updates };54 apiUrl = `${TIKTOK_API_BASE}/campaign/update/`;55 fetchOptions = { method: 'POST', headers, body: JSON.stringify(updateBody) };56 } else {57 return new Response(JSON.stringify({ error: 'Invalid action' }), {58 status: 400,59 headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },60 });61 }6263 const response = await fetch(apiUrl, fetchOptions);64 const data = await response.json();6566 return new Response(JSON.stringify(data), {67 status: response.ok ? 200 : response.status,68 headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },69 });70});Pro tip: TikTok Marketing API responses always include a 'code' field — code 0 means success, any other value is an error even if the HTTP status is 200. Always check response.code === 0 in your frontend before displaying data.
Expected result: The tiktok-ads Edge Function is deployed. Calling it with { action: 'campaigns' } returns your TikTok campaigns including their IDs, names, status, and budget settings.
Build the campaign management dashboard
Build the campaign management dashboard
Use Lovable's chat to build the campaign management and analytics dashboard. The dashboard needs to handle TikTok's three-level hierarchy (campaigns, ad groups, ads) and should surface the metrics most relevant to TikTok's video-first format: video views, video completion rates (at 25%, 50%, 75%, 100%), CTR, and cost-per-result. Start with the campaigns overview. Prompt Lovable to create a table that shows all campaigns with their status, objective, daily budget, spend-to-date, impressions, and CTR. Add a date range picker so users can view performance over different time windows. Include a status toggle for pausing and resuming campaigns. For the reporting view, TikTok's integrated report endpoint is powerful but requires knowing the correct dimension and metric names. Common dimensions are: campaign_id, adgroup_id, ad_id, stat_time_day. Common metrics are: spend, impressions, clicks, ctr, cpc, video_play_actions, video_watched_2s, video_watched_6s, video_views_p25, video_views_p50, video_views_p75, video_views_p100, conversion, cost_per_conversion. For Spark Ads specifically, add a filter in your dashboard for campaign_type = TOPVIEW or BRAND_TAKEOVER to distinguish Spark Ad campaigns from regular In-Feed campaigns. Spark Ads have additional metrics around organic post reach versus paid reach that are useful to surface.
Build a TikTok ads dashboard with three tabs: (1) Campaigns table showing name, status, objective, daily budget, spend, impressions, CTR, and conversions with pause/resume buttons; (2) Ad Groups drilldown that loads when a campaign row is clicked; (3) Performance chart showing daily spend and video completion rates over the last 30 days using data from the tiktok-ads Edge Function report action. Use shadcn/ui Table and Chart components.
Paste this in Lovable chat
Expected result: A TikTok ads dashboard shows campaign performance data populated from the Edge Function. The campaigns table lists all active and paused campaigns with their metrics. Clicking a campaign row loads ad group data. The performance chart shows daily trends.
Common use cases
Multi-account TikTok campaign management dashboard
Build a dashboard for a marketing agency managing TikTok ad accounts for multiple clients. The dashboard shows all campaigns across advertiser accounts, their budget utilization, key performance metrics, and status — all in one view. Managers can pause and resume campaigns and adjust daily budgets without logging into TikTok Ads Manager.
Create a TikTok campaigns dashboard that fetches all campaigns for my advertiser account from the tiktok-ads Edge Function. Show a table with campaign name, status (active/paused), objective, daily budget, spend today, impressions, clicks, CTR, and conversions. Add toggle buttons to pause/resume each campaign and an inline edit for daily budget. Refresh data every 5 minutes.
Copy this prompt to try it in Lovable
Creative performance analyzer for Spark Ads
Build a creative analytics tool that shows how individual TikTok videos (both Spark Ads and In-Feed Ads) are performing. The dashboard compares video completion rates, CTR, and cost-per-result across creatives to help marketers identify winning content and scale it.
Build a creative performance page that fetches ad-level data from the tiktok-ads Edge Function for the past 30 days. Show each ad with its thumbnail, spend, video views, video completion rate (25%, 50%, 75%, 100%), CTR, and CPA. Sort by video completion rate descending to surface the most engaging creatives. Add a filter for date range and ad group.
Copy this prompt to try it in Lovable
Automated budget pacing and alert system
Create a budget monitoring tool that checks daily spend against monthly budget targets for each TikTok campaign, calculates the pacing rate, and sends Slack notifications when campaigns are significantly over- or under-pacing. Alert thresholds are configurable per campaign.
Build a budget pacing tracker that calls the tiktok-ads Edge Function to fetch daily spend for all active campaigns. Calculate the expected daily spend based on monthly budget divided by days in the month. Flag campaigns that are spending more than 120% of expected or less than 80% of expected. Store the pacing status in Supabase and display a red/yellow/green indicator next to each campaign name.
Copy this prompt to try it in Lovable
Troubleshooting
API returns code 40001 with message 'Invalid access token'
Cause: The access token in TIKTOK_ACCESS_TOKEN has expired, was revoked, or does not have the required permissions for the endpoint being called.
Solution: Generate a fresh access token from the TikTok developer portal by re-running the OAuth2 authorization flow for your advertiser account. Update TIKTOK_ACCESS_TOKEN in Cloud → Secrets with the new token. Verify the token has the advertising_management scope which is required for campaign and reporting endpoints.
Report endpoint returns code 40002 'Advertiser not found' or empty data
Cause: The TIKTOK_ADVERTISER_ID does not match a valid advertiser account accessible by the access token, or the advertiser account is in a different TikTok Business Center than the one that issued the token.
Solution: Verify the advertiser ID by logging into TikTok Ads Manager and checking the account settings. The advertiser ID is the numeric string in the URL when viewing a campaign — for example, in /campaign?aadvid=12345678, the advertiser ID is 12345678. Confirm that the access token was generated for the same Business Center that manages this advertiser account.
Report request returns code 0 but the data array is empty even for active campaigns
Cause: The date range in the report request is either outside the campaign's active period, uses the wrong date format, or the reporting lag means same-day data is not yet available.
Solution: TikTok's reporting has a 24-48 hour data lag for some metrics. Use yesterday's date as the end_date rather than today when fetching reports. Dates must be formatted as YYYY-MM-DD strings. Also verify that your campaigns were actively running during the requested date range — campaigns in 'BUDGET_EXCEED' or 'FROZEN' status during the period will show zero metrics.
Campaign status toggle (pause/resume) returns success but the campaign stays in the same status
Cause: TikTok's campaign update endpoint uses specific operation_status values, not simple status strings. The operation_status must be 'ENABLE' (not 'ACTIVE') or 'DISABLE' (not 'PAUSED').
Solution: Update the Edge Function to use the correct TikTok operation status values: send operation_status: 'ENABLE' to activate a campaign and operation_status: 'DISABLE' to pause it. Do not use 'ACTIVE', 'PAUSED', or boolean values — TikTok will silently ignore incorrect status values in some API versions.
1// Correct TikTok campaign status values2const updateBody = {3 advertiser_id: advertiserId,4 campaign_id: params.campaign_id,5 operation_status: params.pause ? 'DISABLE' : 'ENABLE', // Not PAUSED/ACTIVE6};Best practices
- Store all TikTok credentials in Cloud → Secrets, especially the access token which authorizes real advertising spend
- Always check the 'code' field in TikTok API responses — a code of 0 means success; any other value is an error even when HTTP status is 200
- Cache campaign and ad group data in Supabase and refresh every 5 minutes rather than fetching live on every page interaction — TikTok's API has rate limits that can block dashboard refreshes
- Use TikTok's sandbox environment during development to avoid accidentally creating real campaigns or impacting active ad spend
- Include video completion rate metrics (video_views_p25 through video_views_p100) in your reporting — these are TikTok-specific KPIs more meaningful than simple CTR for video ads
- Use 'ENABLE' and 'DISABLE' (not 'ACTIVE'/'PAUSED') as operation_status values when updating campaign status via the API
- Add a date range picker defaulting to the last 7 days — TikTok's integrated report endpoint has a 24-48 hour lag for some metrics, so yesterday should be the default end date
Alternatives
Choose Facebook Ads if you need broader demographic targeting across multiple age groups, image-based ad formats, or deeper integration with Instagram commerce features beyond short-video content.
Choose LinkedIn Ads if your campaigns target B2B decision-makers, professionals, or specific company sizes and job titles rather than consumer audiences on a short-video platform.
Choose Pinterest Ads if your products are visually driven and discovery-oriented (home decor, fashion, food, DIY) and your audience leans toward purchase intent browsing rather than entertainment viewing.
Frequently asked questions
What is the difference between Spark Ads and In-Feed Ads on TikTok?
Spark Ads boost an existing organic TikTok video post as a paid ad — the post keeps its original engagement (likes, comments, shares) and appears in feeds as a sponsored version of the organic content. In-Feed Ads are purpose-built ad creatives uploaded specifically for advertising, with no connection to an organic post. Spark Ads tend to perform better because they feel more authentic to TikTok users, but they require you to either own the organic post or have permission from the creator to boost it.
Does TikTok Marketing API access require a minimum ad spend?
TikTok's Marketing API access requires an approved developer application, but there is no mandatory minimum ad spend to access the API itself. However, TikTok Ads Manager accounts require a minimum deposit (typically $500-$1,000 depending on region) to activate advertising. If you are building for a client or agency, the client's advertiser account must have sufficient funds before campaigns can run, but the API dashboard itself can display data from accounts with any spend level.
How do I handle multiple advertiser accounts in one Lovable dashboard?
For agency dashboards managing multiple clients, store each advertiser ID in a Supabase table linked to a client record rather than hardcoding a single TIKTOK_ADVERTISER_ID in Secrets. Update the Edge Function to accept the advertiser_id as a parameter in the request body, then validate that the requesting user has permission to access that advertiser account. Use Supabase Row Level Security to ensure each user can only query their permitted advertiser accounts.
Why does TikTok's API return code 0 even when there is an error?
TikTok uses its own response envelope format where the HTTP status code is not the primary error indicator. Every successful TikTok API response has a code field at the top level: code: 0 means success, and any non-zero code indicates an error. The message field in the response body provides the human-readable error description. Your Edge Function and frontend must check response.code === 0 before treating the response as successful data.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation