Skip to main content

Starting with the Script API and handling events

This task puts JavaScript in a behavior pack (BP) to react to events and change the world, entities and players. A script starts from the entry file that the one script module in the manifest points to, and the game runs one script tick per game tick (1/20 second). Rule IDs in this wiki cover only JSON UI, so the items in this guide have no rule IDs; judge confidence by the verification level marks at the end of each item.

When to use it​

What you wantMethod in this guideWhen it does not fit
Change the world in response to player actions (item use, block break, join)Subscribe to world.afterEvents and write directly in the callback-
Block an action or change the damageUse event.cancel = true or a writable field in world.beforeEvents, and defer other world changes with system.runAfter events cannot be canceled
Receive commands a player typesRegister a custom command in system.beforeEvents.startupChat interception (chatSend) is beta only
Check periodically or split a large jobsystem.runInterval, system.runJobThere are no events for movement, jumping or starting to sleep, so poll
Keep values in the worldDynamic properties (setDynamicProperty)An ItemStack itself or an entity cannot go into a dynamic property. Use structure storage (Known limits and workarounds)
Draw values on screen (HUD, forms)This guide is not enoughShowing server data on the HUD, Reskinning a server form, Changing Ore UI pages and server-driven DDUI
Run logic with a resource pack aloneNot possible. A resource pack cannot have a scripts folderMake a behavior pack as well
Use HTTP on Realms or a local worldNot possible. @minecraft/server-net is BDS onlyserver-ui, server-net, server-admin, GameTest
Call another add-on's scriptIt cannot be imported. Each pack has its own runtimesystem.sendScriptEvent and system.afterEvents.scriptEventReceive

Minimal example​

A behavior pack that adds 1 to the player's count in a player dynamic property each time the player uses a compass and shows it in an ActionFormData form. The second button clears the count. scripts/main.js and the dependency pair are copied unchanged from the dynamic property example (measured 2026-11-27 on Windows 1.26.65: 1, 2, then 1 after clearing), and the rest of the manifest is the minimal example of the Script API overview that the example followed.

my_script_pack/
manifest.json
scripts/
main.js

manifest.json: it is format_version 2, so the version of the header and modules and min_engine_version are arrays. A dependency version is always a string regardless of the manifest format. Make two new UUIDs for each pack.

{
"format_version": 2,
"header": {
"name": "My Script Pack",
"description": "Compass use counter",
"uuid": "2527cbd4-ce3c-415f-9db5-85cc679d762e",
"version": [1, 0, 0],
"min_engine_version": [1, 21, 100]
},
"modules": [
{
"type": "script",
"language": "javascript",
"uuid": "c2e58bd1-8cd5-4a4a-906e-35dca793ad84",
"version": [1, 0, 0],
"entry": "scripts/main.js"
}
],
"dependencies": [
{ "module_name": "@minecraft/server", "version": "2.7.0" },
{ "module_name": "@minecraft/server-ui", "version": "2.0.0" }
]
}

scripts/main.js:

import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

const USES_KEY = "wiki:compass_uses";

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
if (itemStack.typeId !== "minecraft:compass") return;

const uses = (source.getDynamicProperty(USES_KEY) ?? 0) + 1;
source.setDynamicProperty(USES_KEY, uses);

new ActionFormData()
.title("Compass counter")
.body(`You have used the compass ${uses} times.`)
.button("Close")
.button("Reset count")
.show(source)
.then((r) => {
if (r.canceled) return;
if (r.selection === 1) source.setDynamicProperty(USES_KEY, undefined);
})
.catch((e) => {
console.error(e, e.stack);
});
});
  • Subscribing at module top level is fine. A form show is a world-changing call, so it opens in itemUse, an after event.
  • Dynamic properties are written without declaration, and a missing key is undefined, so read it with ?? 0. Setting the value to undefined deletes it.
  • The count goes up before the form opens, so it goes up even when the form is canceled with UserBusy because another UI is open.
  • If the pack defines blocks or items, put a data module in modules as well. One pack cannot have both data and resources.

Other forms to add to the same pack​

Deferring a write in a before event (official docs example, The 5 most common mistakes):

world.beforeEvents.playerInteractWithBlock.subscribe((e) => {
const p = e.player;
system.run(() => { if (p.isValid) p.setOnFire(5); });
});

Cancel by writing to the event object directly.

world.beforeEvents.playerBreakBlock.subscribe((event) => {
if (event.block.typeId === "minecraft:bedrock") event.cancel = true;
});

Unsubscribing needs the same reference that subscribe returned.

const handler = world.afterEvents.playerSpawn.subscribe((e) => { /* ... */ });
world.afterEvents.playerSpawn.unsubscribe(handler);

Start world access inside worldLoad, and register (custom commands, custom components) only in startup.

system.beforeEvents.startup.subscribe((init) => {
// registry registration only
});

world.afterEvents.worldLoad.subscribe(() => {
world.sendMessage("World loaded");
});

A custom command (a shortened form of the official registration example, not run in game). The permission enum uses the name CommandPermissionLevel from the vanilla metadata (server-bindings 2.10.0).

import { system, CommandPermissionLevel, CustomCommandStatus } from "@minecraft/server";

system.beforeEvents.startup.subscribe((init) => {
init.customCommandRegistry.registerCommand(
{
name: "wiki:uses",
description: "Show compass uses",
permissionLevel: CommandPermissionLevel.Any,
cheatsRequired: false,
},
(origin) => {
const uses = origin.sourceEntity?.getDynamicProperty("wiki:compass_uses") ?? 0;
return { status: CustomCommandStatus.Success, message: `Compass uses: ${uses}` };
}
);
});

The callback runs in restricted execution. Reading a dynamic property is taken to be in the allowed range {inferred}; defer anything that changes the world with system.run.

Must match​

  • The script module in modules has "type": "script", lowercase "language": "javascript", and an "entry" that points to a real file. If the entry file is missing or empty, the result is "could not load main".
  • One pack has one script module. With two, the warning skipped, only one script module allowed per pack appears and only the first module loads {measured}.
  • dependencies is a top-level array. Do not put it inside modules.
  • A script module dependency entry has only module_name and version. Do not write a pack uuid in the same entry. A dependency written by UUID gives a deprecation warning {measured}.
  • A dependency version is always a dot-separated string ("2.7.0"). "*" is invalid on release builds.
  • format_version 2 writes the version of the header and modules and min_engine_version as arrays, 3 as strings. Mixing them can give TypeError: cannot read property 'startup' of undefined. Format 3 effectively requires metadata.authors.
  • min_engine_version is a released version. A value higher than the game or not yet released keeps the pack from importing. Use a value ending in 0 without a hotfix number ([1, 26, 10]).
  • If the version suffix is beta or the major is 0, the world must have the Beta APIs experiment on. An internal suffix is rejected for normal packs {code}.
  • Pair @minecraft/server and @minecraft/server-ui. Pairs that worked: 2.7.0 + 2.0.0 (this example), 2.10.0 + 2.2.0 (26.50), 2.11.0 + 2.3.0 (latest stable from 26.60) {community confirmed}.
  • Do not change the pack and module UUIDs on updates; raise only header.version. Dynamic properties are isolated per script module UUID, so changing the UUID hides the earlier values.
  • The game runs only .js. Compile TypeScript to JS and point the entry at the compiled file.
  • Imports use relative paths with the .js extension. .json imports, folder imports and imports of another add-on's script do not work.
  • Module top level is early execution. Event subscription and the system.run family work, but world.getDimension, world.getAllPlayers, dynamic property writes and form creation fail. Move them inside world.afterEvents.worldLoad or system.run.
  • Before event callbacks and custom command callbacks run in restricted execution. Reads, world.sendMessage and setDynamicProperty work; defer world-changing calls with system.run(() => { ... }) and check isValid again inside.
  • Cancel with event.cancel = true. ({ cancel }) => { cancel = true } changes only a copy. cancel does not end the callback, so return to skip the code after it.
  • Inside a deferred system.run callback the event is already over, so it cannot be canceled.
  • A callback receives one event object. The names differ per event (itemUse has source, entityHurt has hurtEntity).
  • Register custom commands only in system.beforeEvents.startup, and give the name a namespace (ns:cmd). For enums, call registerEnum first and make the parameter name the same as the enum name.
  • A custom command callback returns { status, message } or undefined synchronously. An async callback does not work. message is a string.
  • The default of cheatsRequired is true, so the command does not appear in worlds without cheats and on Realms {community confirmed}.
  • Dynamic property values are boolean, number, string and Vector3. Convert objects with JSON.stringify. One string holds up to 32,767 bytes.
  • An ItemStack is a copy. After setLore or setDynamicProperty, write it back with container.setItem(slot, item) for the change to stay.

Common mistakes​

SymptomCauseFix
The script never runs and there is no logA top-level exception (wrong import path, syntax error) stopped the entry silentlyPut a console.warn at the top of the entry to see whether it runs, and fix the import paths
requested invalid version [...] of [@minecraft/server]The module version does not exist in this gamePick one from the Available versions: list in the same log
requesting dependency on beta APIs [...], but the Beta APIs experiment is not enabled.A beta version or "beta" is used with the experiment offTurn on Beta APIs when creating the world, or use a stable version
version conflict for module [@minecraft/server-bindings]The server and server-ui versions do not pairUse one of the pairs above
cannot read property 'subscribe' of undefinedA renamed or removed event, or a beta-only event (chatSend) with a stable moduleFind the new name in the migration table
Native function [...] cannot be used in restricted execution.The world was changed in a before event or command callbackDefer with system.run
Native function [...] cannot be used in early execution.The world was accessed at module top level or in startupMove it inside worldLoad or system.run
Could not find export '...'An interface (Vector3, StartupEvent, etc.) was imported in .js (from 26.40), or the module version is too lowDo not import type-only names. Raise the module version
A newly created file gives Import not found/reload does not read new filesRejoin the world or restart the game
Dynamic properties disappeared after an updateThe pack or module UUID was changedChanging back to the original UUID shows them again. Updates raise only version
Maximum string size exceededA dynamic property string is over 32,767 bytesSplit it across several keys
Item lore or a dynamic property does not stayOnly the ItemStack copy was changedWrite it back with container.setItem(slot, item)
An item is used twice in playerInteractWithBlock beforeIt fires repeatedly while the button is heldif (!event.isFirstEvent) return;
No player object in playerJoinplayerJoin has only the id and nameUse initialSpawn of playerSpawn, and check isValid after a delay before messages and forms
A custom command is not in the listcheatsRequired defaults to true, or Admin or higher was used on RealmscheatsRequired: false, and GameDirectors on Realms
cannot change parameters ... during reloadCommand parameters were changed and /reload was usedReopen the world fully
console.log does not showGUI Log Level is WarnUse console.warn or set the level to Info
The script stops with InternalError: interruptedThe watchdog caught a long synchronous job in one tickSplit it with system.runJob and reduce logging and allocation in hot loops
Native class [...] not registered for JSClassID after /reloadA stale context remainsUse /reload all or rejoin
TypeScript output gives ReferenceError: 'exports' is not definedmodule is nodenext, so the output is CommonJSSet module to an es2020-style value

Version conditions​

  • On the Windows 1.26.65.1 client the latest stable @minecraft/server is 2.11.0 and the beta is 2.12.0-beta {code}. The matching @minecraft/server-ui is 2.3.0 stable and 2.4.0-beta.
  • A dependency "version": "beta" resolves to the newest beta of that game. You do not need to change the number on each update, but it needs the Beta APIs experiment and breaks when the API changes. A pinned x.y.z-beta.* breaks on every update.
  • 3.0.0-alpha loaded even in a world with all experiments off {measured}. It cannot be assumed to equal the latest 2.x beta, so use stable for released packs.
  • From 2.0.0 module top level is early execution and worldInitialize is gone (startup and worldLoad). 1.x documents and AI-generated code use old APIs such as runCommandAsync, isValid() and world.events.
  • The 26.70 preview has @minecraft/server 2.12.0-rc and 2.13.0-beta, and the message of a custom command result accepts a RawMessage. The npm beta tag points to the beta of the release game, so install preview types with the full version, as in npm i @minecraft/server@2.13.0-beta.1.26.70-preview.26.
  • Block dynamic properties need block JSON format_version 1.26.50 and "minecraft:block_entity": {"dynamic_properties": true}.

How to check​

  1. Put the pack in development_behavior_packs and turn it on in the behavior pack list of the world edit screen. If you use a beta version, also turn on Beta APIs when creating the world.
  2. In the Creator section of the settings, turn on Content Log GUI and Content Log File and set GUI Log Level to Info. The file is in %APPDATA%\Minecraft Bedrock\logs\ (Minecraft Bedrock Preview for the preview).
  3. Enter the world and read the log. Version, dependency and module errors appear when the world loads. If there is nothing, check whether the console.warn at the top of the entry prints.
  4. For the example, use a compass. The form shows 1, using it again shows 2, and after Reset count using it shows 1.
  5. If you changed an existing file, /reload rereads only scripts. If you created a file or changed the manifest, rejoin the world or restart the game.
  6. If you cannot tell which line fails, attach the VS Code extension Minecraft Bedrock Edition Debugger (mojang-studios.minecraft-debugger). targetModuleUuid in launch.json is the script module UUID, the port is 19144, and you type /script debugger connect in the game. Windows needs a loopback exemption once.
  7. If you suspect lag, make a .cpuprofile with /script profiler start, a few minutes of play and /script profiler stop, and open it in VS Code.

Further reading​

Sources
idSourceLicenseCommitAccessed
private-researchPrivate research (-)-2026-11-13
ms-learnMinecraft Creator documentation (Microsoft Learn)CC BY 4.0 (documentation), MIT (code)a9fd1c02026-11-13
bedrock-wikiBedrock WikiCC BY 4.0 (docs/licenses/CC-BY-4.0.md in the repository)0930b392026-11-13
bedrock-samplesMojang bedrock-samplesMinecraft EULA applies, (c) Mojang AB. All rights reserved15701fa9 (guide baseline 46ba6ea)2026-11-13