In this page
SDK JS
What is it?
The GreyCat JS SDK is the official JavaScript (and TypeScript) library used by applications to communicate with a GreyCat Server.
This library is packaged as a platform-agnostic bundle, meaning that it does not require to be run in a browser environment. It is compatible with Node.js (and Bun, deno) and all major Web browsers.
It is available as an ESM re-export from @greycat/web under @greycat/web/sdk
Getting started
touch package.json
Then paste the following content in package.json:
{
"name": "greycat-app",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"dependencies": {
"@greycat/web": "https://get.greycat.io/files/sdk/web/stable/7.8/7.8.0-stable.tgz"
}
}
And install the dependency with:
npm i
First steps
Create a GreyCat project file named project.gcl with the following content:
@expose
fn hello(name: String): String {
return "Hello, ${name}";
}
And start the server with this command:
greycat serve --user=1
--user=1means that all requests are impersonated to be therootuser, effectively bypassing authentication as this is out of the scope of this intro.
Create a JavaScript entry point file named index.js, paste the following:
import "@greycat/web/sdk";
// Initialize the connection with GreyCat using the defaults
await gc.sdk.init();
// Call an @expose'd function
const hello = await gc.project.hello(", world!");
// Say hello!
console.log(hello);
And run that file using Node.js:
node index.js
# Hello, world!
If you see Hello, world! in the console, you effectively used the JS SDK to communicate with a remote GreyCat server.
Running a task and waiting immediately
You can execute a task and wait for its result in a single step using spawnAwait.
This is the simplest way to run a task and immediately retrieve its output.
import assert from "node:assert";
import "@greycat/web/sdk";
const greycat = await gc.sdk.init();
// spawn a task and wait for its result
const res = await greycat.spawnAwait("project::sum", [40, 2]);
assert.equal(res, 42);
This pattern is useful when you don’t need to interact with the task between its creation and completion.
Running a task and waiting later
Alternatively, you can spawn a task without immediately waiting for it to complete. This gives you more control over when the result is retrieved.
import assert from "node:assert";
import "@greycat/web/sdk";
const greycat = await gc.sdk.init();
// spawn the task (returns a handle immediately)
const task = await greycat.spawn("project::sum", [2, 40]);
// ...do other work while the task runs in the background...
// wait for the task to complete and get the result
const res = await task.await();
assert.equal(res, 42);
This pattern is ideal when you want to queue multiple tasks or overlap task execution with other work.