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 want | Method in this guide | When 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 damage | Use event.cancel = true or a writable field in world.beforeEvents, and defer other world changes with system.run | After events cannot be canceled |
| Receive commands a player types | Register a custom command in system.beforeEvents.startup | Chat interception (chatSend) is beta only |
| Check periodically or split a large job | system.runInterval, system.runJob | There are no events for movement, jumping or starting to sleep, so poll |
| Keep values in the world | Dynamic 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 enough | Showing server data on the HUD, Reskinning a server form, Changing Ore UI pages and server-driven DDUI |
| Run logic with a resource pack alone | Not possible. A resource pack cannot have a scripts folder | Make a behavior pack as well |
| Use HTTP on Realms or a local world | Not possible. @minecraft/server-net is BDS only | server-ui, server-net, server-admin, GameTest |
| Call another add-on's script | It cannot be imported. Each pack has its own runtime | system.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
showis a world-changing call, so it opens initemUse, an after event. - Dynamic properties are written without declaration, and a missing key is
undefined, so read it with?? 0. Setting the value toundefineddeletes it. - The count goes up before the form opens, so it goes up even when the form is canceled with
UserBusybecause another UI is open. - If the pack defines blocks or items, put a
datamodule inmodulesas well. One pack cannot have bothdataandresources.
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
moduleshas"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 packappears and only the first module loads{measured}. dependenciesis a top-level array. Do not put it insidemodules.- A script module dependency entry has only
module_nameandversion. Do not write a packuuidin the same entry. A dependency written by UUID gives a deprecation warning{measured}. - A dependency
versionis always a dot-separated string ("2.7.0")."*"is invalid on release builds. format_version2 writes theversionof theheaderand modules andmin_engine_versionas arrays, 3 as strings. Mixing them can giveTypeError: cannot read property 'startup' of undefined. Format 3 effectively requiresmetadata.authors.min_engine_versionis 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
betaor the major is 0, the world must have the Beta APIs experiment on. Aninternalsuffix is rejected for normal packs{code}. - Pair
@minecraft/serverand@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
.jsextension..jsonimports, folder imports and imports of another add-on's script do not work. - Module top level is early execution. Event subscription and the
system.runfamily work, butworld.getDimension,world.getAllPlayers, dynamic property writes and form creation fail. Move them insideworld.afterEvents.worldLoadorsystem.run. - Before event callbacks and custom command callbacks run in restricted execution. Reads,
world.sendMessageandsetDynamicPropertywork; defer world-changing calls withsystem.run(() => { ... })and checkisValidagain inside. - Cancel with
event.cancel = true.({ cancel }) => { cancel = true }changes only a copy.canceldoes not end the callback, soreturnto skip the code after it. - Inside a deferred
system.runcallback the event is already over, so it cannot be canceled. - A callback receives one event object. The names differ per event (
itemUsehassource,entityHurthashurtEntity). - Register custom commands only in
system.beforeEvents.startup, and give the name a namespace (ns:cmd). For enums, callregisterEnumfirst and make the parameternamethe same as the enum name. - A custom command callback returns
{ status, message }orundefinedsynchronously. An async callback does not work.messageis a string. - The default of
cheatsRequiredis true, so the command does not appear in worlds without cheats and on Realms{community confirmed}. - Dynamic property values are
boolean,number,stringandVector3. Convert objects withJSON.stringify. One string holds up to 32,767 bytes. - An ItemStack is a copy. After
setLoreorsetDynamicProperty, write it back withcontainer.setItem(slot, item)for the change to stay.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| The script never runs and there is no log | A top-level exception (wrong import path, syntax error) stopped the entry silently | Put 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 game | Pick 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 off | Turn 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 pair | Use one of the pairs above |
cannot read property 'subscribe' of undefined | A renamed or removed event, or a beta-only event (chatSend) with a stable module | Find 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 callback | Defer with system.run |
Native function [...] cannot be used in early execution. | The world was accessed at module top level or in startup | Move 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 low | Do not import type-only names. Raise the module version |
A newly created file gives Import not found | /reload does not read new files | Rejoin the world or restart the game |
| Dynamic properties disappeared after an update | The pack or module UUID was changed | Changing back to the original UUID shows them again. Updates raise only version |
Maximum string size exceeded | A dynamic property string is over 32,767 bytes | Split it across several keys |
| Item lore or a dynamic property does not stay | Only the ItemStack copy was changed | Write it back with container.setItem(slot, item) |
An item is used twice in playerInteractWithBlock before | It fires repeatedly while the button is held | if (!event.isFirstEvent) return; |
No player object in playerJoin | playerJoin has only the id and name | Use initialSpawn of playerSpawn, and check isValid after a delay before messages and forms |
| A custom command is not in the list | cheatsRequired defaults to true, or Admin or higher was used on Realms | cheatsRequired: false, and GameDirectors on Realms |
cannot change parameters ... during reload | Command parameters were changed and /reload was used | Reopen the world fully |
console.log does not show | GUI Log Level is Warn | Use console.warn or set the level to Info |
The script stops with InternalError: interrupted | The watchdog caught a long synchronous job in one tick | Split it with system.runJob and reduce logging and allocation in hot loops |
Native class [...] not registered for JSClassID after /reload | A stale context remains | Use /reload all or rejoin |
TypeScript output gives ReferenceError: 'exports' is not defined | module is nodenext, so the output is CommonJS | Set module to an es2020-style value |
Version conditions
- On the Windows 1.26.65.1 client the latest stable
@minecraft/serveris2.11.0and the beta is2.12.0-beta{code}. The matching@minecraft/server-uiis2.3.0stable and2.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 pinnedx.y.z-beta.*breaks on every update. 3.0.0-alphaloaded 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
worldInitializeis gone (startupandworldLoad). 1.x documents and AI-generated code use old APIs such asrunCommandAsync,isValid()andworld.events. - The 26.70 preview has
@minecraft/server2.12.0-rcand2.13.0-beta, and themessageof a custom command result accepts a RawMessage. The npmbetatag points to the beta of the release game, so install preview types with the full version, as innpm i @minecraft/server@2.13.0-beta.1.26.70-preview.26. - Block dynamic properties need block JSON
format_version1.26.50 and"minecraft:block_entity": {"dynamic_properties": true}.
How to check
- Put the pack in
development_behavior_packsand 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. - 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 Previewfor the preview). - 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.warnat the top of the entry prints. - For the example, use a compass. The form shows 1, using it again shows 2, and after Reset count using it shows 1.
- If you changed an existing file,
/reloadrereads only scripts. If you created a file or changed the manifest, rejoin the world or restart the game. - If you cannot tell which line fails, attach the VS Code extension Minecraft Bedrock Edition Debugger (
mojang-studios.minecraft-debugger).targetModuleUuidinlaunch.jsonis the script module UUID, the port is 19144, and you type/script debugger connectin the game. Windows needs a loopback exemption once. - If you suspect lag, make a
.cpuprofilewith/script profiler start, a few minutes of play and/script profiler stop, and open it in VS Code.
Further reading
- Script API overview and execution model: Three execution privileges, Tick model and the
system.runfamily, Startup flow of Scripting V2, Manifest layout, File layout and import, Watchdog - Module versions, beta, and changes by version: Specifying versions in the manifest, Changes by version
- Events and combat: Filters and unsubscribing, Handling player join, Migration table
- Custom commands: Permission levels, Permission problems
- Dynamic properties and data storage
- Debugging, performance, tools: Content log and console, VS Code debugger, Profiler
- Pattern recipes, known limits, open questions
- manifest.json: Script module dependency versions, Differences between format_version 2 and 3, min_engine_version
- Server form API and form types: form responses and
UserBusy
| id | Source | License | Commit | Accessed |
|---|---|---|---|---|
private-research | Private research (-) | - | 2026-11-13 | |
ms-learn | Minecraft Creator documentation (Microsoft Learn) | CC BY 4.0 (documentation), MIT (code) | a9fd1c0 | 2026-11-13 |
bedrock-wiki | Bedrock Wiki | CC BY 4.0 (docs/licenses/CC-BY-4.0.md in the repository) | 0930b39 | 2026-11-13 |
bedrock-samples | Mojang bedrock-samples | Minecraft EULA applies, (c) Mojang AB. All rights reserved | 15701fa9 (guide baseline 46ba6ea) | 2026-11-13 |