javascript-state-machine
A javascript finite state machine library
A tiny JavaScript library for defining state machines, systems that can be in exactly one state at a time and move between states through named transitions. Works in both browsers and Node.js with lifecycle hooks and helper methods included.
A finite state machine is a pattern used in programming where a system can be in exactly one state at any given time, and it moves between states through named transitions. This library provides a simple way to define and run such machines in JavaScript, for both browsers and Node.js.
You set up a machine by listing its possible states and the transitions between them. The example in the README models matter: the starting state is solid, and you define transitions like melt (solid to liquid), vaporize (liquid to gas), and condense (gas to liquid). Each transition becomes a method you can call directly on the machine object.
The library also supports lifecycle events, which are functions that run automatically at particular points in a transition: before it starts, after it completes, when leaving a state, or when entering one. This makes it straightforward to attach side effects to state changes without scattering manual checks throughout your code. You can also store arbitrary data on the machine and attach custom methods alongside the state logic.
Helper methods let you ask questions about the current state: whether a given transition is currently allowed, which transitions are possible from where you are, and what all the defined states or transitions are. A factory pattern is also available for creating multiple independent instances from the same definition.
The library is available as an npm package or as a script tag in a browser page. The README notes that version 3.0 was a substantial rewrite from the 2.x series, so existing users should read the upgrade guide before updating. It is released under the MIT license.
Where it fits
- Model a multi-step checkout flow so your app always knows whether the user is in cart, address, payment, or confirmed state.
- Build a traffic light or game character controller where state transitions are named and predictable.
- Add lifecycle hooks to a form wizard so validation code runs automatically when the user leaves each step.
- Create multiple independent instances of the same state machine for parallel workflows in a Node.js application.