TikTok for Developers

Developer Docs

Last updated November 20, 2026

Build Mini Games With Cocos

Turn an existing Cocos Creator project into a TikTok mini game. Build it with the Cocos Creator ByteDance Mini Game target, preview it on your phone with DevTool, integrate the platform features your game needs, and reduce package size before you submit. If core gameplay depends on login or network access, integrate those features before your first test on a device.

The following image shows the workflow. When a check fails, fix the issue and test again.

Five-step Cocos release workflow: prepare, build, phone test, integrate platform features, and release; fix failed checks, rebuild, and retest

Prerequisites

  • You have an editable Cocos Creator project and a compatible Creator version. This guide uses Cocos Creator 3.8.6. Menus and options can differ in other versions.
  • You have a Mini Game app on the Developer Portal and its client key.
  • The TikTok account on your phone is a test user for your app. Developer access to the app and test-user permission for the phone account are set up separately.
  • You have installed DevTool and signed in.

To add a test user, open your app on the Developer Portal and go to Testing permissions > Add a test account, or Roles and access > Test accounts > Add test user, depending on the page you see. Then scan the Developer Portal QR code with the TikTok account you'll test with and complete authorization. This QR code is different from the Client preview QR code you scan in DevTool later.

Keep your game logic. Replace business APIs from other platforms, such as login, ads, and payments, with the corresponding TikTok APIs.

Build your mini game

Use Cocos Creator's built-in ByteDance Mini Game build target to generate the mini game directory. The target outputs the engine scripts, adapter files, and assets. App identity, platform features, testing, and release use TikTok: your client key, the TikTok APIs, DevTool, and the Developer Portal. If your Creator version has no TikTok-specific build target, use the following configuration.

Configure the build

  1. Click Project > Build and create or open a build task.
  2. In the Platform list, select Douyin Microgame (also called ByteDance Mini Game).
  3. Set Start Scene to your entry scene, and include the scenes the build needs.
  4. Set Build Path to build or your own output directory.
  5. Choose the orientation confirmed for your game. Before you use landscape, confirm its availability, submission requirements, and supported TikTok and SDK versions with TikTok developer support.
Cocos Creator build configuration with the platform set to ByteDance Mini Game

During debugging, you can keep Debug turned on to keep logs. When you prepare the upload build, turn off Debug and turn on script compression.

If you use remote assets, configure your own HTTPS asset server and register its domain in your app's development configuration. See Set Up Development Configuration and Load assets remotely.

For more on the build target, see Cocos's ByteDance Mini Game build documentation.

Export the package

  1. Click Build.
  2. When the build completes, click the task's folder icon to open the output directory. The default task usually outputs to bytedance-mini-game. The name can change with the task name.
  3. Check that the output root contains game.js, game.json, and project.config.json.
Windows Explorer showing the bytedance-mini-game output folder, with game.json and project.config.json selected

The output directory is the directory you use with DevTool. File names depend on your Creator version and build settings. A typical output looks like this:

build/bytedance-mini-game/
game.js
game.json
project.config.json
application.js
web-adapter.js
engine-adapter.js
cocos-js/
src/
assets/

Keep the generated engine and adapter files and their loading order. Asset folders depend on your project configuration.

Adapt the exported output

A successful build doesn't mean the game is ready to run in TikTok. Before you debug, check that the output meets the TikTok mini game requirements:

  • Startup entry: game.js is the entry file, and game.json is in the output root.
  • Engine loading order: The engine loads before your game scripts.
  • Package files: The output contains only the files your game needs at runtime.
  • Asset paths: Asset paths resolve correctly in the output directory.
  • Subpackages: Each subpackage root declared in game.json exists in the output and matches its directory.
  • Platform APIs and configuration: Business APIs from other platforms are replaced with TikTok APIs, and your client key, trusted domains, and other platform settings are configured for this mini game.

Make changes in your Cocos project or in a build script you can run again, not in the output directory. Each build overwrites the output.

Preview on your phone

Use Client preview in DevTool to run the exported game in the TikTok app. If the first scene requires login, a network service, or remote assets, configure those first.

  1. In a terminal, go to the exported directory that contains game.js and game.json, and start DevTool:
cd "PROJECT_PATH/build/bytedance-mini-game"
ttmg dev --client-key CLIENT_KEY
  • Replace the following:
    • PROJECT_PATH: the path to your Cocos project.
    • CLIENT_KEY: your app's client key.
  • In DevTool, select Client preview and scan the QR code with the phone account authorized for this app.
  • On the phone, check that the first scene appears, the core interaction works, and required audio and services respond. Then test later scenes and moving the game to the background and back.
  • If a check fails, check the first error in DevTool, fix the source or configuration, rebuild, and test the new export. Preview in Cocos Creator's browser doesn't replace a test in TikTok on a device.

    If DevTool can't load project details, check that your developer account can access the app. If needed, run ttmg login and restart ttmg dev.

    After you change source code or assets, rebuild in Cocos Creator and start or sync DevTool from the new export. Check that the phone loads the new build. For logs, breakpoints, and QR code troubleshooting, see Debug Your Mini Game.

    Integrate platform features

    Call the TikTok Mini Games JavaScript APIs from your Cocos TypeScript scripts, based on what your game needs. Replace login, ad, payment, and sharing calls from other platforms one at a time.

    Games with in-app purchases must integrate silent login. Every mini game must integrate Home Screen Shortcut and Revisit From Profile.

    For the full list of capabilities and requirements, see Develop Your Mini Game.

    Call the SDK from TypeScript

    In a Cocos TypeScript project, call the Mini Games JavaScript SDK through TTMinis.game. The TikTok Mini Games runtime provides this object when the exported game runs in TikTok. You don't install the Unity C# plugin or load the legacy HTML5 minis.js file. Cocos provides the engine and its build adapter. You integrate the platform APIs and their game logic in your project.

    • Put platform calls in a TypeScript component or service under your project's assets directory, and connect them to the right game events.
    • Add the type declarations for the APIs you use, or narrow the global object locally as in the following examples. Type declarations only help compilation. They don't provide the runtime API.
    • Guard each call for environments where the API isn't available.
    • Make changes in the source project or in repeatable build scripts, then rebuild.

    For method signatures, callbacks, error handling, and version requirements, see the Mini Games SDK reference. For platform setup, server responsibilities, and complete flows, see each feature's guide. The DevTool command package is a debugging tool, not the game SDK.

    An available API doesn't prove the game is running in TikTok on a device. The following function reads the launch scene. Call it from your startup component's start() method. It keeps the game running if the read fails.

    function logTikTokLaunch(): void {
      const host = globalThis as typeof globalThis & {
        TTMinis?: {
          game?: { getLaunchOptionsSync?: () => unknown };
        };
      };
      const api = host.TTMinis?.game;
      if (!api || typeof api.getLaunchOptionsSync !== 'function') {
        console.info('Launch options API is unavailable.');
        return;
      }
      try {
        const options = api.getLaunchOptionsSync();
        if (!options || typeof options !== 'object') {
          console.info('Launch options are unavailable.');
          return;
        }
        const scene = (options as { scene?: unknown }).scene;
        if (typeof scene === 'string') {
          console.info('TikTok launch scene:', scene);
        } else {
          console.info('Launch scene is unavailable.');
        }
      } catch (_) {
        console.info('Could not read launch options.');
      }
    }

    This check only reads the platform object and launch parameters. Changing an API prefix doesn't complete login, ads, or payments. Implement and test each flow with the SDK reference and the feature's guide.

    Add silent login

    If your game needs player accounts, saved progress, or in-app purchases, add a component like the following to a node in your startup scene. Call startLogin() from your startup logic, or bind it to a Cocos button.

    Before you use this example, complete your app's privacy and credential setup. The example is an integration skeleton: implement sendCodeToGameServer with your own HTTPS endpoint, and add your own UI states.

    import { _decorator, Component } from 'cc';
    const { ccclass } = _decorator;
    
    type LoginApi = {
      login: (options: {
        success: (result: { code?: string }) => void;
        fail: (error: unknown) => void;
      }) => void;
    };
    
    @ccclass('TikTokLoginExample')
    export class TikTokLoginExample extends Component {
      // Call from your startup flow or bind to a Cocos button click.
      startLogin(): void {
        const host = globalThis as typeof globalThis & {
          TTMinis?: { game?: Partial<LoginApi> };
        };
        const api = host.TTMinis?.game;
        if (!api || typeof api.login !== 'function') {
          console.warn('TikTok login is unavailable in this environment.');
          return; // Show a suitable fallback in your game.
        }
        api.login({
          success: ({ code }) => {
            if (!code) {
              console.warn('Login returned no code.');
              return; // Allow the player to retry.
            }
            // Replace with your own game-server request; do not log the code.
            void this.sendCodeToGameServer(code).catch(() => {
              console.warn('Game server login failed.');
              // Restore your login UI and offer retry.
            });
          },
          fail: () => {
            console.warn('TikTok login failed.');
            // Restore your login UI and offer retry.
          },
        });
      }
    
      private async sendCodeToGameServer(code: string): Promise<void> {
        // Implement: send code over HTTPS to YOUR game server, which exchanges
        // it with TikTok and establishes your game session.
        throw new Error('Implement your game-server login request');
      }
    }

    Send the temporary code to your game server right away. The server exchanges it for the player's TikTok identity and credentials, starts your game session, and returns what your game needs. Never put the client secret or the token exchange in the Cocos client. Register your game server's domain in your app's development configuration.

    A successful client callback only means you received a code. It doesn't mean your server session exists. For the server request, token handling, and troubleshooting, see Silent Login. To get profile data, request it separately with Explicit Authorization.

    Connect features to game events

    Call each platform API from the game event it belongs to:

    Game event

    What to implement and check

    Guide

    Rewarded revive or bonus

    Enable in-app ads and configure an ad unit. From the Cocos button or game-over controller, create and show a rewarded ad. Grant the reward only after the completion result confirms a completed view. Handle closing without completion, unavailable ads, and errors, and prevent duplicate rewards. Remove listeners when you no longer need them.

    In-App Ads, In-App Ads API

    Item purchase

    Enable in-app purchases and integrate silent login. Connect the shop button to your game server's order creation and the client payment call. Verify the order status and deliver the item on the server. Handle cancellation, failure, and recovery without delivering twice.

    In-App Purchases

    Share or invite

    Call the sharing API from the Cocos share button with the query parameters you need. Read the launch or foreground-entry parameters and restore the matching game state. Handle cancellation and failure.

    Sharing API

    Shortcut and return entry

    Connect the prompt and reward flow to the right game UI. Check API availability and eligibility. Grant rewards only after the reward result confirms eligibility.

    Home Screen Shortcut, Revisit From Profile

    For each feature you integrate, test the success and failure paths in the exported build in TikTok on a device. Local simulation and the DevTool mock options test UI and callbacks, but they don't prove real ad delivery or payment. For sharing and the shortcut entry, test the real entry against a released version. A local or preview build can't test the full return journey.

    Reduce package size

    Start with the sizes DevTool reports. For Cocos projects, package limits apply to uncompressed file sizes:

    Package

    Limit

    Total package

    <= 30 MB

    Main package

    <= 4 MB

    Independent subpackage

    <= 4 MB each

    For how regular and independent subpackages are counted, see the package size limits. Don't use the ZIP file size in place of the DevTool pre-check.

    Reduce startup files

    1. Save a version of your project you can restore.
    2. Before you remove assets, check scene and prefab references, and assets your code loads by name or path, such as with resources.load and assetManager.loadBundle. An asset that isn't in the start scene might still be needed in a later level.
    3. After you confirm assets are unused, remove them, compress textures and audio, and strip engine modules one at a time. Keep only what the first scene needs, and load later levels and large assets on demand.
    4. After each change, rebuild, compare the main and total package sizes, and test the first scene, later scenes, and dynamically loaded assets on your target device. Restore any missing assets or modules.

    For more, see Cocos's Asset Manager documentation.

    Move later levels into subpackages

    Organize later levels as Asset Bundles, and select Mini Game Subpackage in Cocos Creator's bundle configuration. After rebuilding, compare game.json subpackages with the exported folders, as described in Cocos's subpackage documentation.

    Call assetManager.loadBundle when the content is needed. Load the bundle's resources or scene only after the bundle loads, and offer a retry on failure. Check whether the startup scene still references shared assets.

    The Cocos subpackage documentation lists limits for other platforms. Don't apply them to TikTok. Check your upload package against the package size limits.

    The Cocos documentation specifies Mini Game Subpackage as the Main Bundle Compression Type. The example in Try the subpackage example uses merge_dep and produces a level2 subpackage. Check that these settings work for your project and devices: after building, check the subpackage directory and game.json, then test loading on your target device.

    Load assets remotely

    To load assets from a server, configure the bundle as remote, set your HTTPS asset address, and register the domain in your app's development configuration. Upload the generated remote files, and keep their directory, names, and version the same as the build. For more, see Cocos's Asset Bundle documentation.

    1. In Cocos Creator's Build panel, set Resource Server Address to your asset server's root, then rebuild.
    2. Upload the entire generated remote/ directory with its structure unchanged.
    3. Check assets.server, remoteBundles, and bundleVers in the build's settings file (src/settings.json in this example). Compare the actual requests with the files on your CDN, including hashed file names.

    When you load a bundle by name, Cocos Creator 3.8.6 downloads from remote/BUNDLE_NAME/ under the server address. A successful bundle callback only loads the bundle entry. Load the assets you need through the bundle, and handle failures.

    Replacing files on the CDN doesn't guarantee that players get them right away. Test old versions, cached versions, and new versions. On a phone, test the first download, entering again, failure and retry, and asset updates.

    Caution: Don't download and run new business code as a remote asset. When you release a new version, keep the assets older game versions need. After splitting assets, test startup and core gameplay again.

    Try the subpackage example

    The Little Wings example, built with Cocos Creator 3.8.6, starts level one from the main package and loads the level2 bundle when the player enters level two. It doesn't include a backend, login, ads, or payments.

    Download: little-wings-cocos-source-en.zip

    To run the example in Cocos Creator, open the game project directory, then open assets/scenes/Main.scene. Select PLAY MEADOW, then use touch or the Space bar to play. Select LOAD LEVEL 2 and BACK TO MEADOW to check the scene changes.

    Note: The example shows how to configure and load a subpackage. It doesn't show download or startup improvements for your game.

    Configure the level2 bundle

    The following illustration shows the settings this example uses. It isn't a Cocos Creator screenshot. For the Creator interface, see Cocos's Mini Game subpackage configuration. That page uses different sample settings, so follow these steps for level2.

    Level2 setup: enable Is Bundle and Independent Config, name it level2, choose Mini Game Subpackage, keep Remote Bundle off
    1. In the Assets panel, select assets/level2, select Is Bundle, and set Bundle Name to level2. Open Level2.scene and check that its component references the configuration and badge in that folder. Level one must not reference those assets directly.
    2. Click Project > Project Settings > Bundle Config, and create a platform configuration. On the Mini Game tab, turn on Independent Config. In the Douyin Microgame (ByteDance Mini Game) row, select Mini Game Subpackage as the compression type, and leave the remote bundle option off.
    3. Return to the assets/level2 folder properties, select that platform configuration, and save. You can name the configuration anything, but Bundle Name must match loadBundle('level2').

    A mini game subpackage isn't the same as a remote bundle. In this example, the subpackage ships in the exported directory and needs no separate CDN deployment.

    Load the scene on demand

    When the player selects level two, block repeated taps while it loads. If loading fails, keep the current scene and allow a retry. The following function is from assets/scripts/LevelLoader.ts in the example:

    import { assetManager, director } from 'cc';
    
    export function openLevel2(status: (message: string) => void, failed: () => void) {
      const started = Date.now();
      status('Loading level2 bundle...');
      console.log('[bird-case] bundle-load-start level2');
      assetManager.loadBundle('level2', (error, bundle) => {
        if (error) {
          console.error('[bird-case] bundle-load-failed', error);
          status('Load failed. Check network, then tap RETRY.');
          failed();
          return;
        }
        console.log('[bird-case] bundle-ready level2', Date.now() - started);
        status('Loading scene and its assets...');
        bundle.loadScene('Level2', (sceneError, scene) => {
          if (sceneError) {
            console.error('[bird-case] scene-load-failed', sceneError);
            status('Scene failed. Check files, then tap RETRY.');
            failed();
            return;
          }
          console.log('[bird-case] scene-ready Level2', Date.now() - started);
          director.runScene(scene);
        });
      });
    }

    openLevel2 doesn't block repeated calls, so prevent duplicate loads in the caller. Set a loading state in your component before you call it, and ignore repeated taps. In the failure callback, restore the state and the retry button. See switchLevel() in the example's assets/scripts/BirdGame.ts.

    In this example, the Cocos adapter handles platform subpackage loading for assetManager.loadBundle, so the game makes no separate platform subpackage call.

    A loaded bundle doesn't mean the scene is running. Check that loadScene and runScene complete:

    • The example logs scene-ready after loadScene, before the switch. director.runScene(scene) launches the scene at the end of the current frame.
    • To clear a shared loading state after launch, pass your own callback as the third argument: director.runScene(scene, undefined, onLaunched). The example doesn't implement this callback.

    If more than one component or entry point can switch scenes, prevent duplicates in a shared game coordinator. This component's state only guards its own calls. Discard stale asynchronous results after the component is destroyed or the player leaves.

    Build and check the output

    1. Build with the platform you selected in Configure the build and Main as the start scene. Level two is in the level2 bundle.
    2. In the output directory, check for game.js, game.json, and subpackages/level2/. Check the subpackage's name and root in game.json:
    {
      "subpackages": [
        { "name": "level2", "root": "subpackages/level2/" }
      ]
    }
  • To change the configuration, change it in Cocos Creator and rebuild. Don't edit the exported files.
  • Check that subpackages/level2/ contains the config file, import/, and native/. MD5 Cache can add a hash to file names. Compare the actual files and dependencies against the scene references and bundle priority.
  • Start DevTool from the export and use Client preview. First check that level one works without selecting level two. Then check loading, the second scene and its logs, returning to level one, the failure message, and retry.
  • Record the first entry, a second entry in the same session, and entry after a restart. Restarting doesn't clear the subpackage cache. Before you treat a download as a cold-cache test, confirm the package cache is actually cleared. To test a failed first download and retry, use a package that isn't cached.

    Fix subpackage loading failures

    Problem

    What to check

    No subpackage in the output

    The Bundle Name, the platform's Mini Game Subpackage configuration, and the declaration in game.json. Then rebuild.

    Level two loads at startup

    An early loadBundle call, or direct references from level one to later content.

    The bundle loads but the scene doesn't appear

    The scene name, scene-load-failed logs, dependencies, and director.runScene.

    Assets stay in the main package

    References, bundle priority, output locations, and dependencies. Then rebuild and compare.

    Upload and submit your game

    1. In Cocos Creator, turn off Debug, turn on script compression, and rebuild.
    2. Run the DevTool pre-check on that export and fix any blocking issues.
    3. Upload the package. For upload steps, see Release Your Mini Game.
    4. On the Developer Portal, check the new code version and open its Preview. Client preview tests your local build, so test the uploaded version in Preview before you submit it.
    5. Submit the same code version you tested. If the package hasn't changed, you can preview it without uploading it again.

    For review and release, see Release Your Mini Game.

    Troubleshooting

    Start at the step that fails, and keep the first error and the steps to reproduce it.

    Problem

    What to check

    The build target is missing

    This guide uses Cocos Creator 3.8.6 and the ByteDance Mini Game target. Check the options in your Creator version.

    DevTool can't find the game entry

    Use the exported directory that contains game.js, game.json, and project.config.json, not the Cocos project root.

    The game works in Cocos Creator but not in TikTok

    The first error, the entry scene, the generated adapter files, and any business APIs from other platforms.

    Assets or later scenes are missing

    Bundle loading, file name case, dependencies, remote domains, and uploaded asset versions.

    The main package is too large

    Engine stripping, subpackage configuration, and shared asset references. Then rebuild and compare the DevTool pre-check.

    If the issue persists, contact TikTok Developer Support. Include your client key; your Cocos Creator, DevTool, and TikTok versions; the device and account region; the game version; the time of the issue; the steps to reproduce it; screenshots or recordings; and relevant logs. Remove secrets, login credentials, and access tokens.

    Next steps

    TikTok for Developers