Node.js and Electron bindings for the Steamworks SDK, maintained as a personal fork of ceifa/steamworks.js.
Introduction, guides and agent skills: https://steamworks.hagicode.com/
This project is a fork of the upstream steamworks.js (Node/Electron bindings) and, through the vendor/steamworks-rs submodule, of steamworks-rs (the Rust bindings it is built on). The Rust side lives in HagiCode-org/steamworks-rs.
It exists for my own development work, not as a general replacement for upstream. It is shaped around two needs:
- Working well with coding agents. The repository carries agent guidance (
AGENTS.md), task-oriented skills for Steam Workshop work (steamworks-js/and thesteamworks-workshop-*folders), and a documentation site built from this README and those skills. - Covering the Steamworks features my projects use. Steam Workshop (UGC) is the most complete area: creating items of any file type, publishing and updating them (additional previews and videos, preview-only and content-only updates, metadata, key-value tags, content descriptors, known game versions, per-language titles and descriptions), item and app dependencies, and the logged-in user's votes, favorites and playtime tracking. Beyond Workshop it covers friends, stats and leaderboards, networking sockets/messages/utils, the server browser, timeline, screenshots and Remote Play.
What that means in practice:
- The npm package is
@hagicode/steamworks.js, not the unscopedsteamworks.js, and it is released on its own schedule. - Changes follow what I need, so there is no promise of staying in step with upstream. If you want the general-purpose library, use upstream.
- Upstream's history is kept. All credit for the original design and implementation goes to the upstream authors, and the MIT license with the original copyright notice (Gabriel Francisco Dos Santos) is kept in LICENSE. The Steamworks SDK files bundled through
vendor/steamworks-rsare not covered by that license and remain under Valve's terms.
Bug reports and pull requests are still welcome. See CONTRIBUTING.md.
const steamworks = require('steamworks.js')
// You can pass an appId, or don't pass anything and use a steam_appid.txt file
const client = steamworks.init(480)
// Print Steam username
console.log(client.localplayer.getName())
// Tries to activate an achievement
if (client.achievement.activate('ACHIEVEMENT')) {
// ...
}You can refer to the declarations file to check the API support and get more detailed documentation of each function.
Every namespace below is on the client returned by init(). Every function, with its parameters, return value and failure cases, is in the API reference, which is rendered from the JSDoc in client.d.ts. Most calls need a running, logged-in Steam client. Anything marked unverified has not been run against a live client yet.
| Area | Namespaces | Where to read more |
|---|---|---|
| Steam Workshop (UGC) | workshop |
The Workshop sections below, and the agent skills for publishing, updating, querying and client state |
| Friends and identity | friends, localplayer, auth |
Friends; the API reference for the rest |
| Stats, achievements, leaderboards | stats, achievement, leaderboard |
Stats, Achievements and Leaderboards |
| Networking | networking, networkingSockets, networkingMessages, networkingUtils |
Networking |
| Servers, lobbies, Remote Play | matchmaking, matchmakingServers, remotePlay |
Server Browser, Timeline, Screenshots and Remote Play; lobbies are in the API reference |
| Timeline and screenshots | timeline, screenshots |
Same section |
| App, overlay, input, cloud, utilities | apps, overlay, input, cloud, utils, callback |
Supplemental Functions; the API reference for the rest |
What the Workshop namespace can do today:
- Read:
getItem,getItems,getAllItems,getUserItems, with additional previews, supported game versions and dependency links on request. - Create and update:
createItem(anyWorkshopFileType),updateItemand its preview-only and content-only helpers, with title and description per language, tags, visibility, metadata, key-value tags, content descriptors, screenshots, YouTube videos and game-version ranges. - Dependencies: required items (
addDependency,removeDependency) and required apps (addAppDependency,removeAppDependency,getAppDependencies). - The logged-in user: subscribe, download and install info, votes, favorites and playtime tracking.
These two parts of the SDK are deliberately not wrapped. This section records the decision and its reasons, so the question is not reopened without new facts. The public API did not change for it: client.d.ts has no remote_storage publish function and no screenshots tagging function.
| Feature | Decision | Checked in the code or SDK headers | Reason | Unverified |
|---|---|---|---|---|
remote_storage publish (PublishWorkshopFile) |
Exclude | The SDK header declares PublishWorkshopFile with the other remote storage calls. Nothing in this repository wraps or calls it. |
The UGC calls this binding already wraps (createItem, updateItem, the dependency and preview calls) cover publishing. A second publish route would need its own tests and skill. |
Whether Steam still accepts this route for current accounts. |
Screenshots tagging (TagPublishedFile) |
Defer | The header declares TagPublishedFile on ISteamScreenshots. The screenshots namespace only hooks the screenshot hotkey. |
The call needs a screenshot handle from the hooked hotkey flow. Without a use case in this repository, a wrapper would ship untested. Reopen it when a consumer needs it. | Whether a tag call succeeds and shows on the item page. It needs a running client. |
Recommendation: keep both out of the public API. When screenshots tagging is needed, start with a live check on a private test item.
To use steamworks.js you don't have to build anything, just install it from npm:
npm i @hagicode/steamworks.jsGuides and agent skills are on the documentation site at https://steamworks.hagicode.com/. To try the latest build from main, install the dev dist-tag: npm i @hagicode/steamworks.js@dev.
If you were using the unscoped upstream steamworks.js package and want this fork instead, update your package.json:
{
"dependencies": {
"@hagicode/steamworks.js": "latest"
}
}Then run pnpm install. Your require('steamworks.js') statements will continue to work without changes.
Steamworks.js is a native module and cannot be used by default in the renderer process. To enable the usage of native modules on the renderer process, the following configurations should be made on main.js:
const mainWindow = new BrowserWindow({
// ...
webPreferences: {
// ...
contextIsolation: false,
nodeIntegration: true
}
})To make the steam overlay working, call the electronEnableSteamOverlay on the end of your main.js file:
require('steamworks.js').electronEnableSteamOverlay()For the production build, copy the relevant distro files from sdk/redistributable_bin/{YOUR_DISTRO} into the root of your build. If you are using electron-forge, look for #75.
You only need to build if you are going to change something on this fork's code. If you just want to use the library in your game, see the installation section.
Make sure you have the latest node.js, Rust and Clang. We also need Steam installed and running.
This project uses git submodules for the steamworks-rs dependency. When cloning the repository, use:
git clone --recurse-submodules https://github.com/HagiCode-org/steamworks.js.gitIf you have already cloned the repository without submodules, initialize them with:
git submodule update --init --recursiveInstall dependencies with pnpm install and then run pnpm run build:debug to build the library.
There is no easy way to build for all targets locally, and you do not need to. Develop and test on your current target. When the code is merged to main, a GitHub Action builds every target and publishes a dev build.
Go to the test/electron directory. There, you can run pnpm install and then pnpm start to run the Electron app.
Click "activate overlay" to test the overlay.
Please see CONTRIBUTING.md for guidelines on commit conventions and the pull request process.
Besides the main preview, a Workshop item can show extra screenshots. Read them with includeAdditionalPreviews, and add more with additionalPreviewPaths (an update that carries only the new images):
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// list: each entry has urlOrVideoId, originalFilename and previewType (ItemPreviewType)
const item = await client.workshop.getItem(itemId, { includeAdditionalPreviews: true })
console.log(item.additionalPreviews)
// add: appended to the item's screenshots; no content and no title change are sent
await client.workshop.updateItem(itemId, { additionalPreviewPaths: ['/abs/path/shot-2.png'] }, appId)
// remove: pass the 0-based indexes from `additionalPreviews`; the main preview is not affected
await client.workshop.updateItem(itemId, { removeAdditionalPreviewIndexes: [0, 2] }, appId)- Removals run before additions in the same update, from the highest index down. Indexes always refer to the list as it was before this update, so read the list again before removing.
- Screenshots cannot be reordered through this API. The main preview is replaced with
previewPath, not removed. - Steam lists screenshots by file name. Send only the files that are not listed yet, otherwise they are added again.
- Adding screenshots needs a Steam client that is running and logged in, and an account that owns the app.
updateItem accepts every field as optional, so a call that carries only previewPath or only contentPath already updates just that part. Two explicit helpers make that intent obvious and check the path before talking to Steam:
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// replace only the main preview image; the mod files are not uploaded
await client.workshop.updateItemPreview(itemId, '/abs/path/preview.png', appId, 'New preview')
// upload only the mod folder; the preview image is not touched
await client.workshop.updateItemContent(itemId, '/abs/path/mod-folder', appId, 'Fix crash on load')- Signature for both:
(itemId, path, appId?, changeNote?).appIddefaults to the app the client was initialized with, andchangeNoteis optional. updateItemPreviewrejects when the path is missing or is not a file.updateItemContentrejects when the path is missing or is not a folder. Both check before any Steam call.- Title, description, tags and visibility are not sent, so they stay as they are. To change them together with a file, keep using
updateItem. - Neither helper reports upload progress. For a large content upload use
updateItemWithCallback.
createItem(appId?, fileType?) creates an empty item. Without fileType it is a Community item, as before. The WorkshopFileType values are Community, Art, Screenshot, Video, Collection, WebGuide and IntegratedGuide.
updateItem accepts these optional fields. A field left out keeps the item's current value:
additionalPreviewVideos: YouTube video IDs, 11 characters each, not URLs. A malformed ID rejects with the entry named, before anything is sent. Whether Steam shows a video added this way is unverified until a live run.metadata: a developer metadata string.keyValueTags:{ clear?, remove?, add? }, applied in the order clear, remove, add.addtakes{ key, value }pairs andremovetakes keys.contentDescriptors:{ remove?, add? }ofWorkshopContentDescriptorvalues, removals first. Only the five SDK values exist, so any other number is refused.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
const { WorkshopFileType, WorkshopContentDescriptor } = client.workshop
const created = await client.workshop.createItem(appId, 1) // 1 = WorkshopFileType.Art
await client.workshop.updateItem(created.itemId, {
metadata: 'v2',
keyValueTags: { clear: true, add: [{ key: 'mode', value: 'hard' }] },
contentDescriptors: { add: [5] }, // 5 = WorkshopContentDescriptor.AnyMatureContent
additionalPreviewVideos: ['dQw4w9WgXcQ'],
}, appId)- Each of these calls changes the item on Steam. Confirm the item and the change first.
- The typings expose no read for an item's metadata, key-value tags or content descriptors, so after a write only the Steam result code can be checked.
workshop.py uploadsends--file-typeand the YouTube videos listed inworkshop.json. It does not send metadata, key-value tags or content descriptors; those are steamworks.js calls only.
A Workshop item can require another item, so Steam installs the required item along with it. addDependency and removeDependency take the parent and the child as bigint ids and resolve with the Steam result code. 1 means OK. Any other code is a Steam failure reason, and it arrives as a resolved number, not a rejection.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
const modId = 123456789n // your mod: an item owned by the logged-in account
const requiredId = 3836453389n // the required child item (Outing Picker)
// mark the child as required by the mod
const added = await client.workshop.addDependency(modId, requiredId)
if (added !== 1) {
console.error(`Steam refused the dependency, result code ${added}`)
}
// remove it again; the result code is returned the same way
const removed = await client.workshop.removeDependency(modId, requiredId)- Both calls need a running, logged-in Steam client, and the parent must be an item the logged-in account owns.
- An id that is negative or does not fit in 64 bits rejects before any Steam call. A failed call with no completion also rejects, and the error says the outcome is unknown, so check the item before retrying.
An item can also require an app, such as a DLC. addAppDependency(itemId, appId) and removeAppDependency(itemId, appId) resolve with the Steam result code, the same way as the item calls above.
getAppDependencies(itemId) resolves with { result, appIds, totalAppDependencies }. Steam sends the list in pages of up to 32, and the binding collects them until the reported total is reached. If appIds is shorter than totalAppDependencies, the list is incomplete. The paging follows the SDK header, and it is unverified against a live Steam client.
These calls act for the logged-in user on Steam, so they change that user's state and not only the item. Each one resolves when Steam confirms it. getUserItemVote is the only one that reads.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
await client.workshop.setUserItemVote(itemId, true) // vote up; false votes down
const vote = await client.workshop.getUserItemVote(itemId) // { votedUp, votedDown, skipped }
await client.workshop.addItemToFavorites(itemId) // appId defaults to the client's app
await client.workshop.removeItemFromFavorites(itemId)
await client.workshop.startPlaytimeTracking([itemId]) // the list must not be empty
await client.workshop.stopPlaytimeTracking([itemId])- Item ID 0, a negative id and an empty playtime list are refused before any Steam call.
- Start and stop playtime tracking in pairs. The SDK header describes these calls as tracking the user's playtime for the listed items; that behavior is unverified against a live client.
- These calls need a running, logged-in Steam client.
An item can declare the game versions (Steam branches such as open_beta or public) it is valid for. Every item returned by a query carries those ranges in supportedGameVersions, and updateItem changes them with requiredGameVersionMin and requiredGameVersionMax:
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// read: one entry per range; an open end is left out (undefined)
const item = await client.workshop.getItem(itemId)
console.log(item.supportedGameVersions) // e.g. [{ minBranch: 'open_beta', maxBranch: 'open_beta' }, { minBranch: 'public' }]
// change: valid for open_beta and every branch published after it; the content is sent in the same update
await client.workshop.updateItem(itemId, {
contentPath: '/abs/path/mod-folder',
requiredGameVersionMin: 'open_beta',
requiredGameVersionMax: '',
}, appId)supportedGameVersionscomes with items fromgetItem,getItems,getAllItemsandgetUserItems. It is an empty list when Steam returns no range for the item.- Both change fields are optional. Setting one changes that end, and the other end is left open. Leaving both out keeps the range as it is.
- Pass both as
""to make the item valid for every game version again. - Steam applies the range only when the same update changes the item's content, so send
contentPathwith it. Otherwise Steam does not apply the range. - Changing the range needs a running, logged-in Steam client and an item the logged-in account owns.
Steamworks.js supports localized content for Steam Workshop items. You can update the title and description for different languages using the language parameter.
// Update English content (backward compatible - no language specified)
await workshop.updateItem(itemId, {
title: "My Mod",
description: "English description"
});
// Update English content (explicitly)
await workshop.updateItem(itemId, {
title: "My Mod",
description: "English description",
language: "english"
});
// Update Chinese content
await workshop.updateItem(itemId, {
title: "我的模组",
description: "中文描述",
language: "schinese"
});Since Steam API only supports updating one language at a time, you need to make multiple updateItem() calls for each language:
// Sequential updates
await workshop.updateItem(itemId, {
title: "My Mod",
description: "English description",
language: "english"
});
await workshop.updateItem(itemId, {
title: "Mon Mod",
description: "Description française",
language: "french"
});
await workshop.updateItem(itemId, {
title: "Mi Mod",
description: "Descripción en español",
language: "spanish"
});Or use Promise.all() for parallel updates:
await Promise.all([
workshop.updateItem(itemId, {
title: "Mein Mod",
description: "Deutsche Beschreibung",
language: "german"
}),
workshop.updateItem(itemId, {
title: "私のMod",
description: "日本語の説明",
language: "japanese"
}),
workshop.updateItem(itemId, {
title: "내 모드",
description: "한국어 설명",
language: "korean"
})
]);Steam supports the following language codes:
| Code | Language | Code | Language |
|---|---|---|---|
english |
English | schinese |
Simplified Chinese |
tchinese |
Traditional Chinese | german |
German |
french |
French | italian |
Italian |
korean |
Korean | spanish |
Spanish |
russian |
Russian | thai |
Thai |
japanese |
Japanese | portuguese |
Portuguese |
polish |
Polish | danish |
Danish |
dutch |
Dutch | finnish |
Finnish |
norwegian |
Norwegian | swedish |
Swedish |
hungarian |
Hungarian | czech |
Czech |
romanian |
Romanian | turkish |
Turkish |
brazilian |
Brazilian Portuguese | bulgarian |
Bulgarian |
greek |
Greek | arabic |
Arabic |
ukrainian |
Ukrainian | vietnamese |
Vietnamese |
Note: If language is omitted, it defaults to "english".
The friends namespace reads the local user's friend list, friend state and avatars, and sends game invites. SteamIDs are bigint values.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// 0x4 = immediate friends (FriendFlags.IMMEDIATE)
for (const friend of client.friends.getFriends(0x4)) {
const state = client.friends.getFriendState(friend.steamId64)
const avatar = client.friends.getMediumAvatar(friend.steamId64) // Buffer of RGBA pixels, or null
console.log(friend.nickName ?? friend.name, state, avatar?.length ?? 0)
}
// Invite a friend to the current game with a connect string
client.friends.inviteUserToGame(friendSteamId, 'lobby=abc')
// Remove the Rich Presence keys set with localplayer.setRichPresence
client.friends.clearRichPresence()getFriendStatereturns aFriendStatevalue;getFriendGamePlayedreturns the AppID of the game a friend is playing, ornull.- Avatars are
nulluntil Steam has loaded them. Callclient.friends.requestUserInformation(steamId64, true)to ask for a user's information, and wait for thePersonaStateChangecallback before reading it again. - Name and state updates arrive through
runCallbacks(), whichinit()already calls on a timer.
stats gains float stats, the achievement count and a request for another user's stats. achievement gains global unlock percentages and the data an achievement page needs: display name, description, hidden flag, unlock time, progress limits and icon. The leaderboard namespace finds and creates leaderboards, uploads scores and downloads entries.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
client.stats.setFloat('distance', 12.5)
console.log(client.stats.getFloat('distance')) // 12.5, or null when the stat is not defined
console.log(client.stats.getNumAchievements())
// Global unlock percentages: call the request first, then read each achievement
await client.achievement.requestGlobalPercentages()
console.log(client.achievement.getAchievedPercent('FIRST_RUN')) // 0 to 100, or null
// Leaderboards: 0 = Ascending, 0 = Numeric; upload with 0 = KeepBest, download with 0 = Global
const board = await client.leaderboard.findOrCreate('Fastest', 0, 0)
if (board) {
const result = await board.uploadScore(0, 1234, []) // null when Steam did not accept the upload
const top = await board.downloadEntries(0, 0, 10, 0) // ranks 0 to 9
console.log(board.getName(), board.getEntryCount(), result, top)
}requestUserStats(steamId64)only starts the request. Its result arrives through theUserStatsReceivedcallback (seecallback.register).- The Promise-returning functions (
requestGlobalPercentages,find,findOrCreate,uploadScore,downloadEntries) resolve when Steam answers. Steam delivers those answers insiderunCallbacks().init()runs it about 30 times a second, so you do not need to call it yourself while the client is initialized. - A Promise rejects with a readable message when Steam reports a failure. When the answer is lost, the message says the outcome is unknown, so check the data before retrying an upload.
achievement.getAll() and achievement.getInfo(name) return what a client needs to list achievements. Call requestGlobalPercentages() first to fill globalPercent.
await client.achievement.requestGlobalPercentages()
for (const item of client.achievement.getAll()) {
// item: { name, displayName?, description?, hidden?, unlocked, unlockTime?, globalPercent?, progressLimits? }
const when = item.unlockTime === undefined ? null : new Date(item.unlockTime * 1000)
console.log(item.displayName ?? item.name, item.unlocked, when, item.globalPercent)
}
// Icon as raw RGBA pixels; loadIcon waits for Steam to fetch it, getIcon does not
const icon = await client.achievement.loadIcon('FIRST_RUN', 3000) // { width, height, rgba: Buffer } or nullunlockTimeis in seconds since 1970-01-01 UTC. It is left out for a locked achievement and for unlocks that Steam has no time for (Steam reports0for unlocks before December 2009).displayName,descriptionandhiddencome from Steam's localized achievement data. They are left out when Steam has no data, for example before the user's stats have arrived.getInforeturnsnullwhen Steam cannot read the achievement (unknown name, stats not received). That is a failed lookup, not a locked achievement.getAllskips such entries, so compare its length withstats.getNumAchievements().names()returns an empty array when the app defines no achievements instead of throwing.progressLimits(alsogetProgressLimits(name)) gives the min and max of the stat that Steam links to the achievement, or is left out when there is none. Steam's achievement API does not return the current value: read the linked stat withstats.getIntorstats.getFloat.indicateProgress(name, current, max)shows the Steam overlay progress notice. It never unlocks the achievement.getIconandloadIconreturnnullwhile Steam has not fetched the icon and when the achievement has no icon. Steam picks the locked or unlocked artwork from the user's state. Convert the RGBA pixels to PNG on your side if you need a file.- Not verified against a live Steam client in this checkout: only the export list and the TypeScript declarations are tested offline.
stats gains other users' stats, global stats with daily history, average-rate stats and the current player count. achievement.getMostAchievedAchievements() returns the global ranking. leaderboard gains attachUgc and downloadEntriesForUsers. utils gains the Steam universe, IPv6 state, file signature check and text filter. apps gains DLC listing and install control, file details, timed trial, beta branches and proof-of-purchase keys.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// Global stats: request first, then read. int64 values are BigInts; history is newest day first
await client.stats.requestGlobalStats(7)
console.log(client.stats.getGlobalInt('total_kills'), client.stats.getGlobalIntHistory('total_kills', 7))
// Achievement ranking, most achieved first; needs requestGlobalPercentages() first
await client.achievement.requestGlobalPercentages()
console.log(client.achievement.getMostAchievedAchievements()) // [{ name, percent, achieved }]
// DLC and beta branches. installDlc and setActiveBeta change the local installation
const dlcs = client.apps.getDlcs() // [{ appId, available, name }]
const betas = client.apps.getBetas() // [{ name, description, buildId, flags, isDefault, isSelected, ... }]
// Text filter: initFilterText() first; 2 = Chat
client.utils.initFilterText()
const filtered = client.utils.filterText(2, 76561198000000000n, 'some chat text') // { text, filteredCount } or nullgetUserIntandgetUserFloatneedrequestUserStats(steamId64)to have completed for that user. They returnnullwhen the stat is missing or the user's stats are not loaded.- Promises from
requestGlobalStats,getNumberOfCurrentPlayers,attachUgc,downloadEntriesForUsers,checkFileSignatureandgetFileDetailsresolve when Steam answers. That happens insiderunCallbacks(), whichinit()runs about 30 times a second. A Promise rejects with a readable message when Steam reports an error. requestGlobalStats(days)accepts at most 60 days, and the global history getters returnnullabove that. The global getters returnnulluntil the request completes.updateAvgRateStatchanges the local stats. Nothing reaches Steam untilstats.store(). Steam keeps the count as a 32-bit float.downloadEntriesForUserstakes at most 100 SteamIDs; more are rejected before Steam is called.attachUgcchanges the user's leaderboard data on Steam.installDlc,uninstallDlc,markContentCorruptandsetActiveBetachange the local installation.setDlcContextonly tells Steam which DLC is being played.requestProofOfPurchaseKeyandrequestAllProofOfPurchaseKeysanswer through theAppProofOfPurchaseKeyResponsecallback (callback.register). The final callback of the full request hasappId0. The keys are secrets: do not log them.- Units:
getEarliestPurchaseUnixTimeis seconds since 1970-01-01 UTC.getDlcDownloadProgressandgetFileDetailsreport bytes as BigInts.getFileDetails().sha1is 40 lowercase hex characters.getSecondsSinceAppActiveandgetSecondsSinceComputerActiveare seconds.getCurrentBatteryPoweris a percentage, and 255 means AC power. - Sync calls return
nullorfalseon failure and do not throw. The SDK header does not say whatgetEarliestPurchaseUnixTimereturns without a purchase, and does not define theavailableflag of a DLC or the flags ofgetFileDetails. - Not verified against a live Steam client: all of the above. Only the export list and the TypeScript types are tested offline.
client.inventory reads and changes the user's Steam Inventory: item instances, item definitions, promotions, prices and purchases. Most calls resolve once Steam has answered.
const { items, timestamp, expired } = await client.inventory.getAllItems()
for (const item of items) {
// item: { itemId: bigint, definition: number, quantity: number, flags: number }
console.log(item.itemId, item.definition, item.quantity)
}
// Changes the real inventory: ask the user before you call this
const { items: changed } = await client.inventory.consumeItem(items[0].itemId, 1)
// Items another player sent: null when Steam rejects the buffer or it belongs to someone else
const verified = client.inventory.deserializeResult(received, senderSteamId)
// Property changes are one batch: set what you need, then submit once
const update = client.inventory.startUpdateProperties()
update?.setInt64(items[0].itemId, 'level', 3n)
await update?.submit()- Each Promise resolves when Steam's
SteamInventoryResultReady_tcallback arrives. Steam delivers that callback insiderunCallbacks(), whichinit()runs on a timer. Every async function takes an optionaltimeoutMs(default 30000). - A Promise rejects with a readable message when Steam reports an error. When no answer arrives within
timeoutMs, the message says the outcome is unknown: the change may still have happened, so check the inventory before you retry. - Functions that grant, create, consume, exchange, trade, buy or submit property changes change the user's real inventory. Ask the user to confirm before you call them.
- Item instance ids, Steam ids and prices are
bigint, because they can exceed 2^53.definition,quantityandflagsarenumber. Prices are in the smallest unit of the currency thatrequestPrices()reports. expired: truemeans Steam may have changed the result since it was made, for example because an item was traded or consumed. The items are still returned.serializeItems(itemIds)returns a Buffer. Steam marks a serialized resultexpiredafter one hour.deserializeResult(data, steamId)is synchronous and returnsnullon failure, so pass the Steam id of the player who sent the buffer.loadItemDefinitions()only starts the load. This binding does not expose Steam's definition-update callback, so it cannot tell you when the definitions are complete.getItemDefinitions()can return an incomplete list until then.startPurchase()resolves when Steam opens the transaction. The user completes the purchase in the Steam overlay, and the final result arrives later through Steam's result-ready callback, not through this Promise.tradeItems()andsendItemDropHeartbeat()are deprecated by Steam. The SDK documents trading as not supported, sotradeItems()is expected to reject.- Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the pure conversion code are tested offline.
localplayeradds the ISteamUser calls that were missing:getHSteamUser(),trackAppUsageEvent(),getUserDataFolder(), the voice calls (startVoiceRecording(),stopVoiceRecording(),getAvailableVoice(),getVoice(),decompressVoice(),getVoiceOptimalSampleRate()),isBehindNat(),advertiseGame(),getGameBadgeLevel(), the phone and two-factor checks,getMarketEligibility(),getDurationControl()andsetDurationControlOnlineState().authaddsrequestEncryptedAppTicket(),getEncryptedAppTicket()andrequestStoreAuthUrl(). The encrypted ticket is requested first, then read;getEncryptedAppTicket()does not call Steam.cloudadds the user-file callsgetQuota(),writeFileAsync(),openWriteStream()(aFileWriteStreamwithwriteChunk(),close()andcancel()),beginFileWriteBatch(),endFileWriteBatch()andgetLocalFileChanges().cloudalso adds the UGC callsdownloadUgc(),downloadUgcToLocation(),getUgcDownloadProgress(),getUgcDetails(),readUgc(),getCachedUgcCount()andgetCachedUgcHandle().- Steam ids and UGC handles are
bigint. A negative id or one of 2^64 or more is rejected before anything is sent. Results that Steam can leave empty come back asnull. - Async functions resolve through
runCallbacks(), whichinit()already calls. There is no timeout: if Steam never answers, the Promise stays pending. ForwriteFileAsync()and thedownloadUgc*()calls, the outcome is then unknown. writeFileAsync()andFileWriteStream.close()change the user's cloud files, anddownloadUgc*()starts network transfers. Ask the user to confirm before you call them.- A
FileWriteStreamthat is garbage-collected withoutclose()orcancel()is closed by the wrapper, which commits the chunks written so far. When that happens depends on the garbage collector, so callclose()orcancel()yourself. - The legacy Workshop publishing calls of
ISteamRemoteStorageare not exposed;ISteamUGCreplaces them (see theworkshopnamespace). - Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the argument checks that run before any Steam call are tested offline.
The friends namespace also covers the rest of ISteamFriends: friends groups, clans and clan officers, clan and friend chat, follower counts, equipped profile items, rich presence reads and clan activity counts. This example shows one call of each kind.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// A cache read: no Steam request. Each group lists its members as SteamID64 bigints.
for (const group of client.friends.getFriendGroups()) {
console.log(group.name, group.members.length)
}
async function readClanChat(clanChatId) {
// 1 = ChatRoomEnterResponse.Success; other values are Steam's failure reasons
if ((await client.friends.joinClanChatRoom(clanChatId)) !== 1) return null
return client.friends.getClanChatMessage(clanChatId, 0) // ChatMessage or null
}
async function readFollowing() {
// One page of the following list, up to 50 SteamIDs per page
const page = await client.friends.enumerateFollowingList(0)
console.log(page.steamIds.length, page.totalCount)
}- Units: SteamIDs and clan chat ids are
bigint. Indexes, counts andtotalCountarenumber.enumerateFollowingList(startIndex)returns at most 50 SteamIDs per page, the SDK'sk_cEnumerateFollowersMaxlimit. - Cache reads (
getFriendGroups(),getClans(),getFriendRichPresence(),getProfileItemPropertyString()) answer from data that Steam already holds. Without that data they returnnull,0or an empty list. Request it first:requestFriendRichPresence()(theFriendRichPresenceUpdatecallback follows), and the Promises ofrequestEquippedProfileItems(),downloadClanActivityCounts(),requestClanOfficerList()andgetClanInfo(). - The Promise calls (
joinClanChatRoom(),getFollowerCount(),isFollowing(),enumerateFollowingList(),requestEquippedProfileItems(),getClanInfo(),downloadClanActivityCounts(),requestClanOfficerList()) resolve throughrunCallbacks(), whichinit()already calls. They reject with Steam's error text when Steam reports a failure. There is no timeout: a call that Steam never answers stays pending. joinClanChatRoom()resolves with aChatRoomEnterResponse. Only1(Success) means the room was joined. Values2to12are the SDK's failure reasons.- Chat messages arrive as callbacks. Register
GameConnectedFriendChatMsg,GameConnectedClanChatMsg,GameConnectedChatJoinandGameConnectedChatLeavewithcallback.register(), and callsetListenForFriendsMessages(true)before you expect friend messages. The callbacks fire only fromrunCallbacks(). getClanChatMessage(clanChatId, index)andgetFriendMessage(steamId, index)return aChatMessageornull.sendClanChatMessage()andreplyToFriendMessage()return a boolean, which istrueonly when Steam accepts the message. Not verified: the order of the message index and what Steam returns for an index past the end.- Not verified against a live Steam client: no call was made against a Steam account in this checkout. Also unverified: a clan's name before its download, a friend's Steam level before Steam loads it, the value of an empty rich presence key, and what
registerProtocolInOverlayBrowser()does in the overlay. The export list, the TypeScript declarations, the enum values and the callback numbers are tested offline.
Sends HTTP requests through the Steam client. It needs init() and a running, logged-in Steam client.
const client = steamworks.init(480)
const response = await client.http.request({
method: 'GET',
url: 'https://example.com/api/items',
query: { page: '1' },
headers: { Accept: 'application/json' },
responseHeaders: ['ETag'],
timeoutMs: 10000,
})
console.log(response.status, response.headers.ETag, response.body.toString('utf8'))request()resolves for every answer the server gives, including404and500, so checkstatusyourself. It rejects when the request cannot be created or sent, when Steam refuses a header or option, when Steam cannot complete the request, when no answer comes, or when the request times out.- Units:
timeoutMsis a total time limit in milliseconds. Unlike the inactivity timeout, it does not reset when data arrives. Steam's default is no total limit. - Methods:
GET,HEAD,POST,PUT,DELETE,OPTIONSandPATCH, in any letter case.queryis added to the URL forGETand sent as form data for other methods.formis sent as form data.body(aBuffer) needs a method that accepts a body, cannot be combined withformorquery, and usescontentType(defaultapplication/octet-stream). responseHeadersnames the response headers to return. Steam cannot list all of them, so name each one you need. The response has no status text, because the SDK does not provide one.- Cookies:
client.http.createCookieContainer(allowResponsesToModify)makes a container that lasts for this process only. Pass it ascookieContainerand add cookies withsetCookie(host, url, cookie). - The promise resolves through
runCallbacks(), whichinit()already calls. - Not verified against a live Steam client: how HTTPS certificates are checked against a browser's rules, and what
requireVerifiedCertificate: falsedoes.
Ping locations, data centers (POPs), fake IP addresses and config values. These functions need init(). Reads that Steam cannot answer yet return null.
const client = steamworks.init(480)
client.networkingUtils.initRelayNetworkAccess()
// Ping data takes a few seconds to appear after relay access starts.
const here = client.networkingUtils.getLocalPingLocation()
const pops = client.networkingUtils.getPops() // id, code (for example 'iad') and ping for each data center
const ms = here ? client.networkingUtils.estimatePingFromLocalHost(here.location) : nullgetLocalPingLocation()returns{ location, ageSeconds }, ornullwhen Steam has no ping data yet. Passlocationonly to the functions in this namespace, and do not parse it yourself.- Units: pings are milliseconds, ages are seconds, and
getLocalTimestamp()returns microseconds as abigint. That timestamp is comparable only within one run of the process. estimatePingFromLocalHost()andestimatePingBetweenLocations()returnnullwhen Steam cannot estimate, and throw when a location text is not understood.checkPingDataUpToDate(maxAgeSeconds)returnsfalsewhen the data is older than that, and Steam then starts a new measurement. Call it only when you need fresh data now, because Steam refreshes the data on its own.getRealIdentityForFakeIp()throws with Steam's reason when the address is not a fake IP (InvalidParameter) or the mapping is unknown (NoMatch). Steam keeps the mapping for active connections and for a short time after they close.- Config values: the
setGlobalConfigValue*andsetConnectionConfigValue*functions returntruewhen Steam accepts the value andfalsewhen it refuses it. Connection functions take the raw connection handle as a number. TheConnectionobject does not expose that handle yet.getConfigValue(valueId, connection?)returns a number forint32andfloatvalues, abigintforint64values, a string forstringvalues, ornull. UsegetConfigValueInfo()for a value's name, type and scope, anditerateGenericEditableConfigValues()to list the value numbers. - Not in this binding:
SetDebugOutputFunction, theSetGlobalCallback_*functions,SetGlobalConfigValuePtr, andSetConfigValue/SetConfigValueStruct. They need C function pointers orvoid*arguments. - Not verified against a live Steam client: the byte order of IPv4 numbers in
isFakeIpv4()andgetIpv4FakeIpType(), when ping data first appears, and whether every data center reports a code.
Event handles and game phases on the Steam timeline. These functions need init(). If the Steam client does not provide the timeline, the functions that change it do nothing.
const client = steamworks.init(480)
const { TimelineEventClipPriority } = client.timeline
const event = client.timeline.startRangeTimelineEvent('Boss fight', 'Round 1', 'steam_victory', 0, 0, TimelineEventClipPriority.Featured)
if (event !== null) client.timeline.endRangeTimelineEvent(event, 0)
client.timeline.setGamePhaseId('chapter-1')
const answer = await client.timeline.doesGamePhaseRecordingExist('chapter-1')- Event handles are
bigintvalues, andnullmeans the timeline is unavailable. A handle is valid only in this run of the game. Passing a value that is not a handle from this API throws. - Units: offsets and durations are seconds, measured from now. Negative offsets are in the past.
recordingMsandlongestClipMsare milliseconds. - A range event must be ended with
endRangeTimelineEvent(). Steam discards range events that are still open when the game exits. doesEventRecordingExist()anddoesGamePhaseRecordingExist()return promises. They resolve duringrunCallbacks()and reject when the timeline is unavailable or Steam cannot answer.- A phase ID is at most 63 bytes and must not contain a NUL character. Calls with a longer ID throw.
clipPriorityisNone,StandardorFeatured.- Not verified against a live Steam client: what the overlay shows for
openOverlayToGamePhase()andopenOverlayToTimelineEvent(), and how the timeline behaves on Steam clients that do not support it.
Two families of networking APIs coexist. The networking namespace is the original P2P packet API (sendP2PPacket, readP2PPacket, acceptP2PSession), and it is unchanged. The new networkingSockets, networkingMessages and networkingUtils namespaces wrap Steam's Networking Sockets, Networking Messages and Networking Utils interfaces.
networkingsends unreliable or reliable packets to a SteamID and reads them back in arrival order. There is no connection object, so you cannot close one peer or tell when it dropped.networkingSocketscreates listen sockets and connections (by IP address or by SteamID), sends and receives messages with send flags, and groups connections into poll groups. Connections are objects withclose, and state queries show whether each one is open.networkingMessagesis connectionless, like UDP: send to a SteamID on a channel, receive by channel, and handle session requests and failures. Steam creates the underlying session implicitly.networkingUtilsstarts relay network access and reports its availability.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// Relay access and authentication: start them early if you expect relayed or authenticated connections
client.networkingUtils.initRelayNetworkAccess()
console.log(client.networkingUtils.getRelayNetworkStatus()) // NetworkingAvailability value
client.networkingSockets.initAuthentication()
// Host: poll the listen socket without waiting, accept connecting peers and take the connection when it is connected
const listen = client.networkingSockets.createListenSocketIp('0.0.0.0:27015')
const event = listen.tryReceiveEvent() // null when nothing is pending
if (event && event.kind === 0 /* Connecting */) {
event.accept()
}
if (event && event.kind === 1 /* Connected */) {
const connection = event.takeConnection()
connection.send(Buffer.from('hello'), 8) // 8 = reliable
console.log(connection.receive(16))
}
// Client: connect by IP address, then close with a reason
const connection = client.networkingSockets.connectByIpAddress('203.0.113.5:27015')
connection.setUserData(1n)
connection.close(1000, 'done', true)
// Messages: accept requests from Steam users and read channel 3
client.networkingMessages.onSessionRequest((request) => request.accept())
client.networkingMessages.sendMessageToUser(friendSteamId, 8, Buffer.from('hi'), 3)
console.log(client.networkingMessages.receiveMessagesOnChannel(3, 10))- Send flags are a bitmask of Steam's
k_nSteamNetworkingSend_*values:0unreliable,8reliable,1no Nagle delay. Invalid addresses and closed handles fail with a readable error. - Listen socket events and session requests are only produced while
runCallbacks()runs.init()already calls it about 30 times a second. - A connection or request you never close or answer is closed or rejected when its JavaScript object is garbage collected. Close connections explicitly.
- Connections and messages need a Steam network path, so they cannot be exercised offline. The offline smoke test only checks that these functions are exported.
matchmakingServers lists game servers and queries single servers. timeline marks game state and events for Steam's timeline. screenshots hooks the screenshot hotkey and adds images to the Steam library. remotePlay lists Remote Play Together sessions and sends invites.
const steamworks = require('steamworks.js')
const client = steamworks.init(appId)
// Server list: request, read, then release it
const list = client.matchmakingServers.lanServerList(appId)
try {
for (let i = 0; i < list.getServerCount(); i++) {
const server = list.getServerDetails(i) // ip, port, name, map, players, maxPlayers, ping
console.log(server.name, server.players, server.maxPlayers, server.ping)
}
} finally {
list.release()
}
// Single server: these are Promises and reject when the server does not answer
const ping = await client.matchmakingServers.pingServer('192.168.1.10', 27015)
const players = await client.matchmakingServers.playerDetails('192.168.1.10', 27015)
const rules = await client.matchmakingServers.serverRules('192.168.1.10', 27015)
// Timeline: 0 = Playing (the game mode values are Playing, Staging, Menus, LoadingScreen)
client.timeline.setGameMode(0)
client.timeline.addEvent('icon', 'Boss defeated', '', 0, -5, 5, 1) // clip priority 1 = Standard
// Screenshots: with the hook on, the hotkey raises ScreenshotRequested instead of Steam taking the picture
client.screenshots.hookScreenshots(true)
client.screenshots.triggerScreenshot()
// Remote Play Together
for (const session of client.remotePlay.sessions()) {
console.log(session.sessionId, session.steamId64, client.remotePlay.sessionDetails(session.sessionId))
}
client.remotePlay.invite(friendSteamId)- Steam fills a server list over time, through callbacks that
init()pumps automatically. Read the count after a short wait, not right after the request. The single-server functions are Promises that resolve the same way. - Release every server list request when you finish with it. Methods called after
release()throw a readable error. - Invalid IPv4 addresses, negative durations and strings with NUL characters are rejected with a readable error before any Steam call.
timelinecalls are silent when the Steam timeline interface is unavailable.
These functions extend existing namespaces. Nothing that existed before has changed.
const client = steamworks.init(appId)
// apps: the launch command line, and a query parameter from a Steam link such as steam://run/480//mode=demo
client.apps.launchCommandLine()
client.apps.launchQueryParam('mode') // '' when the parameter is absent
// utils: overlay and UI state
client.utils.isOverlayEnabled()
client.utils.isSteamInBigPictureMode()
client.utils.getUiLanguage() // for example 'english'
// input: digital and analog action data, and the origins bound to an action
const pressed = client.input.getDigitalActionData(controllerHandle, actionHandle).state
const stick = client.input.getAnalogActionData(controllerHandle, analogHandle) // { x, y, active }
const origins = client.input.getDigitalActionOrigins(controllerHandle, actionSetHandle, actionHandle)
const label = client.input.getStringForActionOrigin(origins[0] ?? 0)
// networking: P2P packets on a channel, and closing a session
client.networking.sendP2PPacketOnChannel(friendSteamId, SendType.Reliable, Buffer.from('hi'), 2)
client.networking.isP2PPacketAvailableOnChannel(2)
client.networking.closeP2PSession(friendSteamId)
// cloud: share a file (a Promise), stop syncing it, and choose the platforms it syncs to
const shareHandle = await client.cloud.shareFile('save.json')
client.cloud.forgetFile('save.json')
client.cloud.setSyncPlatforms('save.json', 0 /* SyncPlatform.None */)getStringForActionOriginandgetGlyphForActionOriginreturn an empty string for an origin number that Steam does not define.getSyncPlatformsrejects when a file syncs to a combination of platforms, because a singleSyncPlatformvalue cannot describe it.shareFileresolves once Steam answers, which happens throughrunCallbacks().init()runs it for you.
This fork has its own release line and publishes to npm as @hagicode/steamworks.js. It does not follow upstream's release numbers. Releases are automated:
- Dev builds: Every push to the
mainbranch publishes a build to the npmdevdist-tag for testing - Release drafts: Every push to
mainupdates one draft GitHub release for the nextvX.Y.Z, drafted by hagi-release-drafter. It is never published automatically - Official releases: Publish the draft in the GitHub UI. That creates the
vX.Y.Ztag, and the tag publishes the npmlatestversion
Release notes are automatically generated from Conventional Commit messages. See CONTRIBUTING.md for the commit message format.