Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Puter
https://github.com/heyputer/puter
Admin
๐ The Internet OS! Free, Open-Source, and Self-Hostable.
Tokens:
836,610
Snippets:
5,296
Trust Score:
9.6
License:
AGPL-3.0
Update:
1 week ago
Context
Chat
Benchmark
76
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Get started with Puter on localhost Source: https://github.com/heyputer/puter/wiki/_Footer Clone the Puter repository, install dependencies, and start the development server on localhost. ```sh git clone https://github.com/HeyPuter/puter.git npm install npm run start ``` -------------------------------- ### Local Development Setup (bash) Source: https://github.com/heyputer/puter/blob/main/README.md Clones the Puter repository, installs dependencies, and starts the development server. After running, Puter should be available at http://puter.localhost:4100. ```bash git clone https://github.com/HeyPuter/puter cd puter npm install npm start ``` -------------------------------- ### Create hello-puter.js extension with endpoint and event listener Source: https://github.com/heyputer/puter/wiki/contributors-extensions-README This is the quickstart example for a Puter extension. It registers a GET endpoint at /hello-puter that responds with a greeting based on the actor type, and listens to the core.email.validate event to block emails containing 'evil'. The extension global and use are available at load time. ```javascript // You can get definitions exposed by Puter via `use` const { UserActorType, AppUnderUserActorType } = use.core; // Endpoints can be registered directly on an extension extension.get('/hello-puter', (req, res) => { const actor = req.actor; // Make a string "who" which says: // "<username>", or: // "<app> acting on behalf of <username>" let who = 'unknown'; if ( actor.type instanceof UserActorType ) { who = actor.type.user.username; } if ( actor.type instanceof AppUnderUserActorType ) { who = actor.type.app.name + ' on behalf of ' + actor.type.user.username; } res.send(`Hello, ${who}!`); }); // Extensions can listen to events and manipulate Puter's behavior extension.on('core.email.validate', event => { if ( event.email.includes('evil') ) { event.allow = false; } }); ``` -------------------------------- ### Local Development Setup Source: https://github.com/heyputer/puter/blob/main/src/docs/README.md Clone the docs repository, install dependencies, and run the development server. The server launches at http://127.0.0.1:8080 or the next available port. ```bash git clone https://github.com/HeyPuter/docs cd docs npm install npm run dev ``` -------------------------------- ### Docker Compose Setup (Linux/macOS) Source: https://github.com/heyputer/puter/blob/main/doc/i18n/README.en.md Set up and start Puter using Docker Compose on Linux or macOS. Downloads the docker-compose.yml file and launches the stack. ```bash mkdir -p puter/config puter/data sudo chown -R 1000:1000 puter wget https://raw.githubusercontent.com/HeyPuter/puter/main/docker-compose.yml docker compose up ``` -------------------------------- ### Example: Get a subdomain with puter.hosting.get() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/get.md Demonstrates creating a random website, retrieving it with get(), and cleaning up. The promise rejects if the subdomain does not exist. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // (1) Create a random website let subdomain = puter.randName(); const site = await puter.hosting.create(subdomain, '.') puter.print(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`); // (2) Retrieve the website using get() const site2 = await puter.hosting.get(site.subdomain); puter.print(`Website retrieved: subdomain=${site2.subdomain}.puter.site UID=${site2.uid}<br>`); // (3) Delete the website (cleanup) await puter.hosting.delete(subdomain); })(); </script> </body> </html> ``` -------------------------------- ### Install and use Puter.js with npm Source: https://github.com/heyputer/puter/blob/main/src/docs/src/frameworks.md Install the Puter.js NPM library and use it in any framework-agnostic application. The JavaScript example imports the default export and calls puter.ai.chat with a simple message. ```bash npm install @heyputer/puter.js ``` ```javascript import puter from "@heyputer/puter.js"; puter.ai.chat("hello world"); ``` -------------------------------- ### Install Puter.js via NPM Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md Install the Puter.js package using npm. This is the first step for using Puter.js in a project. ```plaintext npm install @heyputer/puter.js ``` -------------------------------- ### Docker Compose Setup (Windows) Source: https://github.com/heyputer/puter/blob/main/doc/i18n/README.en.md Set up and start Puter using Docker Compose on Windows PowerShell. Creates the config and data directories, downloads docker-compose.yml, and launches the stack. ```powershell mkdir -p puter cd puter New-Item -Path "puter\config" -ItemType Directory -Force New-Item -Path "puter\data" -ItemType Directory -Force Invoke-WebRequest -Uri "https://raw.githubusercontent.com/HeyPuter/puter/main/docker-compose.yml" -OutFile "docker-compose.yml" docker compose up ``` -------------------------------- ### Install Playwright browsers Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md One-time setup commands to install necessary dependencies and Playwright browsers. ```sh cd /path/to/puter/src/puter-js npm install npm run playwright:install ``` -------------------------------- ### Example: Create a random app then get it Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/get.md Demonstrates creating an app with a random name, retrieving it via puter.apps.get(), and cleaning up. The promise rejects if the app does not exist. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // (1) Generate a random app name to make sure it doesn't already exist let appName = puter.randName(); // (2) Create the app await puter.apps.create(appName, "https://example.com"); puter.print(`"${appName}" created<br>`); // (3) Retrieve the app using get() let app = await puter.apps.get(appName); puter.print(`"${appName}" retrieved using get(): id: ${app.uid}<br>`); // (4) Delete the app (cleanup) await puter.apps.delete(appName); })(); </script> </body> </html> ``` -------------------------------- ### Connect to an app's key-value store and interact Source: https://github.com/heyputer/puter/blob/main/src/docs/src/cli.md Example session connecting to the 'notes' app. The prompt shows the connected app and key count. Methods like set, get, and list are available bare and results are awaited. ```console $ puter kv connect notes โ Connected to notes (app-1f2e3d4cโฆ) ยท 12 keys kv(notes)> set("greeting", "hi") true kv(notes)> get("greeting") 'hi' kv(notes)> list("gre", true) [ { key: 'greeting', value: 'hi' } ] ``` -------------------------------- ### Send a GET request with puter.net.fetch() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Networking/fetch.md Complete HTML example that loads the Puter.js library, sends a GET request to example.com, reads the response as text, and prints it as a code block using puter.print(). ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // Send a GET request to example.com const request = await puter.net.fetch("https://example.com"); // Get the response body as text const body = await request.text(); // Print the body as a code block puter.print(body, { code: true }); })() </script> </body> </html> ``` -------------------------------- ### move() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that creates a directory, writes a file, stats it, moves it into the directory, and prints a confirmation. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const dirname = puter.randName(); await puter.fs.mkdir(dirname); await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); await item.move(dirname); puter.print(`Moved hello.txt into ${dirname}`); })(); </script> </body> </html> ``` -------------------------------- ### mkdir() Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Example demonstrating how to create a subdirectory inside an existing directory using the mkdir method. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const dirname = puter.randName(); await puter.fs.mkdir(dirname); const dir = await puter.fs.stat(dirname); await dir.mkdir('subdir'); puter.print(`Created subdir inside ${dirname}`); })(); </script> </body> </html> ``` -------------------------------- ### Start Puter desktop Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Commands to navigate to the monorepo root and start the Puter desktop environment. ```sh cd /path/to/puter npm start ``` -------------------------------- ### Install and run MailHog Source: https://github.com/heyputer/puter/wiki/contributors-email_testing Download the MailHog binary, make it executable, and run it. This starts the local email server that captures outgoing emails. ```bash # Install MailHog wget https://github.com/mailhog/MailHog/releases/download/v1.0.1/MailHog_linux_amd64 chmod +x MailHog_linux_amd64 ./MailHog_linux_amd64 ``` -------------------------------- ### copy() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that creates a directory, writes a file, stats it, copies it into the directory, and prints a confirmation. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const dirname = puter.randName(); await puter.fs.mkdir(dirname); await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); await item.copy(dirname); puter.print(`Copied hello.txt into ${dirname}`); })(); </script> </body> </html> ``` -------------------------------- ### Create, get, and delete a hosted website using puter.hosting Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/hosting-get.html Use this snippet to create a website with a random subdomain, retrieve its details, and delete it. The example writes the hosted URL and retrieved subdomain/UID to the document. It cleans up by deleting the website after retrieval. ```javascript (async () => { // (1) Create a random website let subdomain = puter.randName(); const site = await puter.hosting.create(subdomain, '.') document.write(`Website hosted at: ${site.subdomain}.puter.site (This is an empty website with no files)<br>`); // (2) Retrieve the website using get() const site2 = await puter.hosting.get(site.subdomain); document.write(`Website retrieved: subdomain=${site2.subdomain}.puter.site UID=${site2.uid}<br>`); // (3) Delete the website (cleanup) await puter.hosting.delete(subdomain); })(); ``` -------------------------------- ### read() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that writes a file, stats it, reads it, and prints the text content. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); const blob = await item.read(); puter.print(await blob.text()); })(); </script> </body> </html> ``` -------------------------------- ### write() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that writes a file, stats it, overwrites its contents, and prints a confirmation. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); await item.write('Updated contents!'); puter.print('File updated'); })(); </script> </body> </html> ``` -------------------------------- ### readdir() Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Example demonstrating how to list the contents of a directory using the readdir method. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const dirname = puter.randName(); await puter.fs.mkdir(dirname); await puter.fs.write(dirname + '/hello.txt', 'Hello, world!'); const dir = await puter.fs.stat(dirname); const children = await dir.readdir(); children.forEach((child) => puter.print(child.name + '<br>')); })(); </script> </body> </html> ``` -------------------------------- ### Create, get, and delete a Puter app Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/app-get.html Demonstrates the full lifecycle of a Puter app: generate a unique name with puter.randName(), create it with puter.apps.create(), retrieve it with puter.apps.get(), and delete it with puter.apps.delete(). The example prints the app name and its uid to the console. ```javascript (async () => { // (1) Generate a random app name to make sure it doesn't already exist let appName = puter.randName(); // (2) Create the app await puter.apps.create(appName, "https://example.com"); puter.print(`"${appName}" created<br>`); // (3) Retrieve the app using get() let app = await puter.apps.get(appName); puter.print(`"${appName}" retrieved using get(): id: ${app.uid}<br>`); // (4) Delete the app (cleanup) await puter.apps.delete(appName); })(); ``` -------------------------------- ### Interacting with another app using AppConnection Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/AppConnection.md This example demonstrates a parent app launching a child app, sending a message, and handling the response. The parent app uses puter.ui.launchApp to start the child and listens for messages via the child object. ```html <html> <head> <title>Parent app</title> </head> <body> <script src="https://js.puter.com/v2/"></script> <script> // This app is the parent // Launch child (1) const child = await puter.ui.launchApp('child'); // Listen to messages from the child app. (5) child.on('message', msg => { console.log('Parent app received a message from child:', msg); console.log('Closing child app.'); // Close the child (6) child.close(); }); // Send a message to the child (2) child.postMessage('Hello!'); </script> </body> </html> ``` ```html <html> <head> <title>Child app</title> </head> <body> <script src="https://js.puter.com/v2/"></script> <script> // This app is the child // Get a connection to our parent. const parent = puter.ui.parentApp(); if (!parent) { // We were not launched by the parent. // For this example, we'll just exit. puter.exit(); } else { // We were launched by the parent, and can communicate with it. // Any time we get a message from the parent, show it in an alert dialog. (3) parent.on('message', msg => { puter.ui.alert(msg); // Send a message back (4) // Messages can be any JS object that can be cloned. parent.postMessage({ name: 'Nyan Cat', age: 13 }); }); } </script> </body> </html> ``` -------------------------------- ### delete() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that writes a file, stats it, deletes it, and prints a confirmation. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); await item.delete(); puter.print('File deleted'); })(); </script> </body> </html> ``` -------------------------------- ### rename() example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/fsitem.md Complete HTML example that writes a file, stats it, renames it, and prints a confirmation. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { await puter.fs.write('hello.txt', 'Hello, world!'); const item = await puter.fs.stat('hello.txt'); await item.rename('renamed.txt'); puter.print('File renamed'); })(); </script> </body> </html> ``` -------------------------------- ### Example: Create a simple website displaying 'Hello world!' Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/create.md Complete HTML example that creates a random directory, writes an index.html with 'Hello, world!', hosts it under a random subdomain, and prints a link. Requires the Puter.js script and uses puter.randName(), puter.fs.mkdir(), puter.fs.write(), and puter.hosting.create(). ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // (1) Create a random directory let dirName = puter.randName(); await puter.fs.mkdir(dirName) // (2) Create 'index.html' in the directory with the contents "Hello, world!" await puter.fs.write(`${dirName}/index.html`, '<h1>Hello, world!</h1>'); // (3) Host the directory under a random subdomain let subdomain = puter.randName(); const site = await puter.hosting.create(subdomain, dirName) puter.print(`Website hosted at: <a href="https://${site.subdomain}.puter.site" target="_blank">https://${site.subdomain}.puter.site</a>`); })(); </script> </body> </html> ``` -------------------------------- ### TL;DR: Setup and run e2e tests Source: https://github.com/heyputer/puter/blob/main/src/puter-js/tests/e2e/README.md Commands for one-time setup (copy .env.example, set PUTER_ADMIN_PASSWORD) and running tests headless, headed, or with video recording. ```sh # one-time setup cp tests/e2e/.env.example tests/e2e/.env $EDITOR tests/e2e/.env # set PUTER_ADMIN_PASSWORD from the npm start banner # run npm run test:e2e # headless npm run test:e2e:headed # watch the browser npm run test:e2e:record # save video for every test ``` -------------------------------- ### Start puter-js dev server Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Commands to start the development server for puter.js, which serves the test fixture on localhost:8080. ```sh cd /path/to/puter/src/puter-js npm start ``` -------------------------------- ### Use Puter.js in the browser (NPM) Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md Import the puter object from the package and use it to call AI chat. This example shows a simple chat request. ```js import { puter } from "@heyputer/puter.js"; // Example: Use AI to answer a question puter.ai.chat(`Why did the chicken cross the road?`).then(console.log); ``` -------------------------------- ### Booting Puter with Kernel Modules Source: https://github.com/heyputer/puter/wiki/backend-contributors-modules Example of initializing the Puter kernel and adding required modules in run-selfhosted.js. ```javascript const { Kernel, CoreModule, DatabaseModule, LocalDiskStorageModule, SelfHostedModule } = (await import('@heyputer/backend')).default; const k = new Kernel(); k.add_module(new CoreModule()); k.add_module(new DatabaseModule()); k.add_module(new LocalDiskStorageModule()); k.add_module(new SelfHostedModule()); k.boot(); ``` -------------------------------- ### GET /group/list - Response Example Source: https://github.com/heyputer/puter/wiki/api-group Example JSON response from the /group/list endpoint, showing owned groups and groups the user is a member of. ```json { "owned_groups": [ { "uid": "c3bd4047-fc65-4da8-9363-e52195890de4", "metadata": {}, "members": [ "default_user" ] } ], "in_groups": [ { "uid": "c3bd4047-fc65-4da8-9363-e52195890de4", "metadata": {}, "members": [ "default_user" ] } ] } ``` -------------------------------- ### Initialize .env file for testing Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Commands to navigate to the project directory and create a local .env file from the provided example. ```sh cd /path/to/puter/src/puter-js cp tests/e2e/.env.example tests/e2e/.env ``` -------------------------------- ### Using core.config to get origin Source: https://github.com/heyputer/puter/wiki/contributors-extensions-definitions Retrieves the configured origin using the core.config namespace. The example registers a GET route with noauth enabled and sends the config.origin value as the response. ```javascript const config = use('core.config'); extension.get('/get-origin', { noauth: true }, (req, res) => { res.send(config.origin); }) ``` -------------------------------- ### Count Records per Group: get order-counts Source: https://github.com/heyputer/puter/blob/main/src/docs/src/recipes/keep-an-index-in-sync.md Reads the order-counts key to get all counts in one small read. The comment shows an example result: { open: 12, shipped: 40 }. ```javascript const counts = await puter.kv.get('order-counts') ?? {}; // { open: 12, shipped: 40 } ``` -------------------------------- ### Underscore convention example Source: https://github.com/heyputer/puter/wiki/planning-alternatives_to_$ Uses keys starting with '_' for metadata, with '_' indicating the schema. Backwards-compatible with responses not using '_', but restricts valid JSON keys. ```json { "_": "api:thing", "_version": "v1.0.0", "some": "info" } ``` -------------------------------- ### Dollar-sign convention example Source: https://github.com/heyputer/puter/wiki/planning-alternatives_to_$ Uses keys starting with '$' for metadata, with '$' indicating the schema. Backwards-compatible with responses not using '$', but restricts valid JSON keys. ```json { "$": "api:thing", "$version": "v1.0.0", "some": "info" } ``` -------------------------------- ### Initialize Puter GUI with gui() Source: https://github.com/heyputer/puter/wiki/prod Include gui.js and call gui() on page load. All options shown are optional, including gui_origin, api_origin, hosting_domain, max_item_name_length, and require_email_verification_to_publish_website. ```html <script type="text/javascript" src="./dist/gui.js"></script> <script type="text/javascript"> window.addEventListener('load', function() { // Initialize the GUI. All options are optional! gui({ // The origin of the app. This is the base URL of the GUI. gui_origin: "https://puter.com", // The origin of the API. This is the base URL of the API endpoints that the GUI will call for all its operations. api_origin: "https://api.puter.com", // The domain under which user websites are hosted. hosting_domain: "puter.site", // The maximum length of file/directory names. max_item_name_length: 500, // If GUI has to enforce email verification before allowing user to publish a website. require_email_verification_to_publish_website: true, }) }); </script> ``` -------------------------------- ### Create an app pointing to example.com Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/create.md Creates an app with a random name and indexURL https://example.com, prints the app name and UID, then deletes the app for cleanup. Requires the Puter.js script from https://js.puter.com/v2/. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // (1) Generate a random app name let appName = puter.randName(); // (2) Create the app and prints its UID to the page let app = await puter.apps.create(appName, "https://example.com"); puter.print(`Created app "${app.name}". UID: ${app.uid}`); // (3) Delete the app (cleanup) await puter.apps.delete(appName); })(); </script> </body> </html> ``` -------------------------------- ### Run locally with npm run dev Source: https://github.com/heyputer/puter/blob/main/src/mcp-connector/README.md Installs dependencies and starts the development server on http://localhost:8787. ```bash cd src/mcp-connector npm install npm run dev # builds, then wrangler dev โ serves on http://localhost:8787 ``` -------------------------------- ### Watch Puter logs during first boot Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md First boot takes ~30s while MariaDB initialises and Puter applies the schema and default apps. Use this to monitor startup progress. ```bash docker compose logs -f puter ``` -------------------------------- ### Include Puter.js via CDN script tag Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md Include the Puter.js script from the CDN. This is the simplest way to add Puter.js to a web page. ```html <script src="https://js.puter.com/v2/"></script> ``` -------------------------------- ### Host a directory with puter.hosting.create Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/hosting-create.html Creates a random directory, writes an index.html file with 'Hello, world!', and hosts it under a random subdomain using puter.hosting.create. The resulting URL is written to the document. ```javascript (async () => { // (1) Create a random directory let dirName = puter.randName(); await puter.fs.mkdir(dirName) // (2) Create 'index.html' in the directory with the contents "Hello, world!" await puter.fs.write(`${dirName}/index.html`, '<h1>Hello, world!</h1>'); // (3) Host the directory under a random subdomain let subdomain = puter.randName(); const site = await puter.hosting.create(subdomain, dirName) document.write(`Website hosted at: <a href="https://${site.subdomain}.puter.site" target="_blank">https://${site.subdomain}.puter.site</a>`); })(); ``` -------------------------------- ### Use Puter.js in Node.js with init Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md Initialize Puter.js with an auth token using the init function. The token is typically stored in an environment variable. ```js import { init } from "@heyputer/puter.js/src/init.cjs"; const puter = init(process.env.puterAuthToken); // Example: Use AI to answer a question puter.ai.chat("What color was Napoleon's white horse?").then(console.log); ``` -------------------------------- ### Syntax: puter.hosting.create() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/create.md Shows the two call signatures for puter.hosting.create(): one with subdomain and dirPath strings, and one with an options object. The options object requires an absolute root_dir path. ```javascript puter.hosting.create(subdomain, dirPath) puter.hosting.create(options) ``` -------------------------------- ### Example: Get the environment in which Puter.js is running Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/env.md Loads Puter.js from the CDN and prints the environment value using puter.print(). The output will be one of the documented environment strings. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("Environment: " + puter.env); </script> </body> </html> ``` -------------------------------- ### Example: Revoke a read URL Source: https://github.com/heyputer/puter/blob/main/src/docs/src/FS/revokeReadURL.md HTML page that writes a file, gets a read URL, prints it, then revokes it. The revoke call stops the URL from serving the file. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { await puter.fs.write('~/shared.txt', 'temporary contents'); const url = await puter.fs.getReadURL('~/shared.txt'); puter.print(`Readable at: ${url}<br>`); await puter.fs.revokeReadURL(url); puter.print('Revoked โ the URL no longer serves the file.'); })(); </script> </body> </html> ``` -------------------------------- ### Connect a custom domain to a website (HTML example) Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/attach.md Complete HTML example that creates a website and lets the user attach a custom domain. Uses puter.hosting.create and puter.hosting.attach, prints the domain status and DNS records. If the user cancels, prints 'No domain was chosen.' ```html <html> <body> <button id="attach">Use my own domain</button> <script src="https://js.puter.com/v2/"></script> <script> document.getElementById('attach').addEventListener('click', async () => { // (1) Create a website to connect the domain to const site = await puter.hosting.create(puter.randName(), '.'); // (2) Let the user pick or add a domain for it const domain = await puter.hosting.attach(site.subdomain); if (!domain) { puter.print('No domain was chosen.'); return; } puter.print(`${domain.hostname} is ${domain.status}.<br>`); for (const record of domain.records) { puter.print(`${record.type} ${record.name} โ ${record.value}<br>`); } }); </script> </body> </html> ``` -------------------------------- ### Example: Get the signed-in user Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Auth/getUser.md HTML page that loads the Puter.js library and calls puter.auth.getUser() to fetch the user object, then prints it as JSON using puter.print(). ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.auth.getUser().then(function(user) { puter.print(JSON.stringify(user)); }); </script> </body> </html> ``` -------------------------------- ### Full production index.html example Source: https://github.com/heyputer/puter/wiki/prod Complete HTML page that loads Puter with all necessary meta tags, favicons, and branding assets. It includes the GUI script and initializes it on window load. ```html <!DOCTYPE html> <html lang="en"> <head> <title>Puter</title> <meta name="author" content="Puter Technologies Inc."> <meta name="description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time."> <meta name="facebook-domain-verification" content="e29w3hjbnnnypf4kzk2cewcdaxym1y" /> <link rel="canonical" href="https://puter.com"> <!-- Meta meta tags --> <meta property="og:url" content="https://puter.com"> <meta property="og:type" content="website"> <meta property="og:title" content="Puter"> <meta property="og:description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time."> <meta property="og:image" content="./dist/images/screenshot.png"> <!-- Twitter meta tags --> <meta name="twitter:card" content="summary_large_image"> <meta property="twitter:domain" content="puter.com"> <meta property="twitter:url" content="https://puter.com"> <meta name="twitter:title" content="Puter"> <meta name="twitter:description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time."> <meta name="twitter:image" content="./dist/images/screenshot.png"> <!-- favicons --> <link rel="apple-touch-icon" sizes="57x57" href="./dist/favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="./dist/favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="./dist/favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="./dist/favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="./dist/favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="./dist/favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="./dist/favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="./dist/favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="./dist/favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="./dist/favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="./dist/favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="./dist/favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="./dist/favicons/favicon-16x16.png"> <link rel="manifest" href="./dist/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="./dist/favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!-- Preload images when applicable --> <link rel="preload" as="image" href="./dist/images/wallpaper.webp"> </head> <body> <!-- Load the GUI script --> <script type="text/javascript" src="./dist/gui.js"></script> <!-- Initialize GUI when document is loaded --> <script type="text/javascript"> window.addEventListener('load', function() { gui() }); </script> </body> </html> ``` -------------------------------- ### Obtain auth token via browser login Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md If your environment has browser access, you can obtain a token via browser login using getAuthToken, then initialize Puter.js with it. ```js import { init, getAuthToken } from "@heyputer/puter.js/src/init.cjs"; const authToken = await getAuthToken(); // performs browser based auth const puter = init(authToken); ``` -------------------------------- ### Handle cancellation with undefinedOnCancel Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/showSaveFilePicker.md Uses the undefinedOnCancel property to get a promise that resolves to undefined if the user cancels the picker. The example checks if the result is undefined to detect cancellation. ```javascript const file = await puter.ui.showSaveFilePicker('Hello world!', 'hello.txt').undefinedOnCancel; if (file === undefined) { // the user closed the picker without saving } ``` -------------------------------- ### Start a server and reply to clients Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/serve.md HTML page that loads Puter.js, creates a peer server, prints the invite code, and listens for connections to send and receive messages. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const server = await puter.peer.serve(); puter.print(`Invite code: ${server.inviteCode}`); server.addEventListener('connection', (event) => { const conn = event.conn; conn.addEventListener('open', () => { conn.send('Hello from the server!'); }); conn.addEventListener('message', (msg) => { puter.print('Client says:', msg.data); }); }); })(); </script> </body> </html> ``` -------------------------------- ### Basic Usage: Get worker information Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/get.md HTML example that loads the Puter.js library and calls puter.workers.get('my-api'). If the worker exists, it prints the WorkerInfo object; otherwise it prints 'Worker not found!'. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // Get a worker's information const workerInfo = await puter.workers.get('my-api'); if (workerInfo) { puter.print(`Worker information: ${JSON.stringify(workerInfo, null, 2)}`); } else { puter.print('Worker not found!'); } })(); </script> </body> </html> ``` -------------------------------- ### Get current application ID example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/appID.md HTML page that loads the Puter.js library and prints the App ID using puter.appID. The script tag must be included before using the puter object. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("App ID: " + puter.appID); </script> </body> </html> ``` -------------------------------- ### Example: Show the app's window Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/showWindow.md HTML page that loads the Puter.js library and calls puter.ui.showWindow() to display the app window. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ui.showWindow(); </script> </body> </html> ``` -------------------------------- ### Get the max key size example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/MAX_KEY_SIZE.md HTML page that loads the Puter.js library and prints the maximum key size using puter.print. The script tag includes the library from https://js.puter.com/v2/. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("Max Key Size: " + puter.kv.MAX_KEY_SIZE); </script> </body> </html> ``` -------------------------------- ### Create a window with options Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/createWindow.md HTML example that loads the Puter.js library and creates a window with a title, content, and various configuration options such as centering, resizability, and taskbar visibility. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> // create the window puter.ui.createWindow({ title: 'Cool Title', content: `<h1 style="text-align:center;">My little test window!</h1>`, disable_parent_window: true, width: 300, height: 300, is_resizable: false, has_head: true, center: true, show_in_taskbar: false, }) </script> </body> </html> ``` -------------------------------- ### Verify service registration with _init Source: https://github.com/heyputer/puter/wiki/backend-howto_make_driver Implement an _init method to log a message after a delay, confirming the service is loaded during startup. ```javascript class PrankGreetService extends BaseService { async _init () { // Wait for 5 seconds await new Promise(rslv => setTimeout(rslv), 5000); // Display a log message this.log.noticeme('Hello from PrankGreetService!'); } } ``` -------------------------------- ### Start a new notification in a group Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Notifications/markShown.md Demonstrates marking a notification as shown so the next one in the group is a new notification. The example prints whether the second notification replaced the first and whether the third is new. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const first = await puter.notifications.notify({ title: '1 new message', group: 'inbox' }); // (1) Unshown, so the next one in the group replaces it and keeps its uid const second = await puter.notifications.notify({ title: '2 new messages', group: 'inbox' }); puter.print(`replaced: ${second === first}<br>`); // (2) Marked shown, so the next one in the group is a new notification await puter.notifications.markShown(second); const third = await puter.notifications.notify({ title: '1 new message', group: 'inbox' }); puter.print(`new notification: ${third !== second}<br>`); })(); </script> </body> </html> ``` -------------------------------- ### Service configuration JSON example Source: https://github.com/heyputer/puter/wiki/src-backend-services-config Example of a Puter configuration file with a single service entry. The service configuration is placed under the "services" property, and each service has its own object with arbitrary keys. ```json { "services": { "my-service": { "somekey": "some value" } } } ``` -------------------------------- ### Test Worker Endpoints with puter.workers.exec Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/router.md Example of testing deployed worker endpoints using puter.workers.exec. Shows GET and POST requests with JSON body and headers, logging the parsed responses. ```javascript // Test your worker endpoints const workerUrl = "https://your-worker.puter.work"; // Test GET endpoint const response = await puter.workers.exec(`${workerUrl}/api/hello`); const data = await response.json(); console.log(data); // Test POST endpoint const postResponse = await puter.workers.exec(`${workerUrl}/api/data`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: "test", value: "hello" }), }); const postData = await postResponse.json(); console.log(postData); ``` -------------------------------- ### config.json protocol and S3 public endpoint Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md In config.json, switch the protocol to https with pub_port 443 and update the S3 public endpoint to https://s3.puter.localhost. This is part of the TLS setup for public installs. ```json { "protocol": "https", "pub_port": 443 } ``` ```json "s3": { "s3Config": { "publicEndpoint": "https://s3.puter.localhost", ... } } ``` -------------------------------- ### Host a Static Website with puter.hosting.create Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/intro-hosting.html Use this snippet to host a static website on a random subdomain. It creates a directory with puter.fs.mkdir, writes an index.html file with puter.fs.write, and calls puter.hosting.create with a random subdomain. The resulting site URL is printed using puter.print. ```javascript (async () => { // (1) Create a random directory let dirName = puter.randName(); await puter.fs.mkdir(dirName) // (2) Create 'index.html' in the directory with the contents "Hello, world!" await puter.fs.write(`${dirName}/index.html`, '<h1>Hello, world!</h1>'); // (3) Host the directory under a random subdomain let subdomain = puter.randName(); const site = await puter.hosting.create(subdomain, dirName) puter.print(`Website hosted at: <a href="https://${site.subdomain}.puter.site" target="_blank">https://${site.subdomain}.puter.site</a>`); })(); ``` -------------------------------- ### Use Puter.js in the browser (CDN) Source: https://github.com/heyputer/puter/blob/main/src/docs/src/getting-started.md A complete HTML page that includes the CDN script and uses puter.ai.chat. Note: serve the page over HTTP, not from file://, because Puter identifies your app by its origin. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat(`Why did the chicken cross the road?`).then(puter.print); </script> </body> </html> ``` -------------------------------- ### Sign in with user action Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/auth-sign-in.html This example demonstrates how to trigger the signIn() method from a button click event listener. It includes error handling and displays the result or error using puter.print(). ```javascript document.getElementById('sign-in').addEventListener('click', async () => { // signIn() will resolve when the user has signed in. try{ let user = await puter.auth.signIn(); puter.print('Signed in:<br>' + JSON.stringify(user)); }catch(error){ puter.print('Error:<br>' + JSON.stringify(error)); } }); ``` -------------------------------- ### Retrieve a key-value pair with puter.kv.get Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/kv-get.html Creates a key-value pair using puter.kv.set, then retrieves it with puter.kv.get and prints the result. The output shows 'Key-value pair 'name' created/updated' followed by 'Name is: Puter Smith'. ```javascript (async () => { // (1) Create a new key-value pair await puter.kv.set('name', 'Puter Smith'); puter.print("Key-value pair 'name' created/updated<br>"); // (2) Retrieve the value of key 'name' const name = await puter.kv.get('name'); puter.print(`Name is: ${name}`); })(); ``` -------------------------------- ### Build Sharp from Source on FreeBSD Source: https://github.com/heyputer/puter/wiki/self_hosters-first_run_issues Steps to build the sharp module from source and link it to the project on FreeBSD. ```bash pkg install vips git clone --depth=1 https://github.com/lovell/sharp.git cd sharp yarn install sudo npm link ``` -------------------------------- ### Healthy startup log output Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Example of a healthy startup log showing config override, MySQL migrations, and applied migration files. ```text [config] override from /etc/puter/config.json [mysql] running migrations from /opt/puter/dist/src/backend/clients/database/migrations/mysql: <n> file(s) [mysql] applied mysql_mig_1.sql (...) ... ```