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:
470,360
Snippets:
3,464
Trust Score:
9.6
License:
AGPL-3.0
Update:
1 month ago
Context
Chat
Benchmark
70.21
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 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 ``` -------------------------------- ### 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; } }); ``` -------------------------------- ### 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 ``` -------------------------------- ### Run Puter locally with git clone and npm start Source: https://github.com/heyputer/puter/blob/main/README.md Clones the Puter repository, installs dependencies, and starts the development server. After running these commands, Puter should be available at http://puter.localhost:4100. ```bash git clone https://github.com/HeyPuter/puter cd puter npm install npm start ``` -------------------------------- ### 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 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"); ``` -------------------------------- ### Run the MCP connector locally Source: https://github.com/heyputer/puter/blob/main/src/mcp-connector/README.md Commands to install dependencies and start 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Complete HTML example of puter.peer.serve() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/serve.md Full HTML page that loads Puter.js, creates a peer server, prints the invite code, and handles connection events. Use this as a starting point for building a real-time serverβclient interaction where the server sends a greeting to each client and logs incoming 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> ``` -------------------------------- ### 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> ``` -------------------------------- ### 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' } ] ``` -------------------------------- ### 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> ``` -------------------------------- ### Example: Creating a window with puter.ui.createWindow() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/createWindow.md A complete HTML example that loads the Puter.js library and creates a window with various options like title, content, size, and behavior. ```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> ``` -------------------------------- ### Example: Flushing the Key-Value Store Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/flush.md This example demonstrates creating key-value pairs, listing them, flushing the store, and verifying that the store is empty. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // (1) Create a number of key-value pairs await puter.kv.set('name', 'Puter Smith'); await puter.kv.set('age', 21); await puter.kv.set('isCool', true); puter.print("Key-value pairs created/updated<br>"); // (2) Rretrieve all keys const keys = await puter.kv.list(); puter.print(`Keys are: ${keys}<br>`); // (3) Flush the key-value store await puter.kv.flush(); puter.print('Key-value store flushed<br>'); // (4) Retrieve all keys again, should be empty const keys2 = await puter.kv.list(); puter.print(`Keys are now: ${keys2}<br>`); })(); </script> </body> ``` -------------------------------- ### 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 ``` -------------------------------- ### Create a random app then get it Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/get.md HTML example that loads the Puter.js library, generates a random app name, creates the app, retrieves it with puter.apps.get(), prints the app's UID, and deletes the app for cleanup. ```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> ``` -------------------------------- ### 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> ``` -------------------------------- ### Use OpenAI voices Source: https://github.com/heyputer/puter/blob/main/src/docs/src/AI/txt2speech.md Example using the OpenAI provider with model 'gpt-4o-mini-tts', voice 'alloy', response_format 'mp3', and instructions for a cheerful tone. Uses async/await to get the audio element. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <button id="play">Use OpenAI voice</button> <script> document.getElementById('play').addEventListener('click', async ()=>{ const audio = await puter.ai.txt2speech( "Hello! This sample uses the OpenAI alloy voice.", { provider: "openai", model: "gpt-4o-mini-tts", voice: "alloy", response_format: "mp3", instructions: "Sound cheerful but not overly fast." } ); audio.play(); }); </script> </body> </html> ``` -------------------------------- ### Example: Sign-in button with puter.auth.signIn() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Auth/signIn.md HTML example that includes the Puter script and a button that triggers signIn() on click. The promise resolves with the sign-in result, which is printed using puter.print(). ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <button id="sign-in">Sign in</button> <script> // Because signIn() opens a popup window, it must be called from a user action. document.getElementById('sign-in').addEventListener('click', async () => { // signIn() will resolve when the user has signed in. await puter.auth.signIn().then((res) => { puter.print('Signed in<br>' + JSON.stringify(res)); }); }); </script> </body> </html> ``` -------------------------------- ### 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> ``` -------------------------------- ### 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); })(); ``` -------------------------------- ### 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> ``` -------------------------------- ### Example of puter.ui.setMenubar implementation Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/setMenubar.md A complete HTML example demonstrating how to initialize the Puter SDK and configure a menubar with nested menus and click actions. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ui.setMenubar({ items: [ { label: 'File', items: [ { label: 'Action', action: () => { alert('Action was clicked!'); } }, { label: 'Sub-Menu', items: [ { label: 'Action 1', action: () => { alert('Action 1 was clicked!'); } }, { label: 'Action 2', action: () => { alert('Action 2 was clicked!'); } }, ] }, ] }, ] }); </script> </body> </html> ``` -------------------------------- ### Complete Worker Router Implementation Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/router.md A full example demonstrating multiple endpoints including GET, POST, parameter handling, KV storage, file system operations, and a catch-all 404 handler. ```js // Health check router.get("/health", async () => { return { status: "ok", timestamp: new Date().toISOString(), }; }); // User management API router.post("/api/users", async ({ request, user }) => { const userInfo = await user.puter.getUser(); // Store user data const userId = `user_${Date.now()}`; await me.puter.kv.set(userId, { email: userInfo.email, name: userInfo.username, }); return { userId, user: { email: userInfo.email, username: userInfo.username, uuid: userInfo.uuid, }, }; }); router.get("/api/users/:id", async ({ params }) => { const userId = params.id; if (!userId.startsWith("user_")) // security check return new Response("Invalid userID!"); const userData = await me.puter.kv.get(userId); if (!userData) { return new Response( JSON.stringify({ error: "User not found", }), { status: 404, headers: { "Content-Type": "application/json" }, } ); } return { userId, user: userData }; }); // File operations router.post("/api/files/upload", async ({ request }) => { const formData = await request.formData(); const file = formData.get("file"); if (!file) { return new Response( JSON.stringify({ error: "No file provided", }), { status: 400, headers: { "Content-Type": "application/json" }, } ); } const fileName = `upload-${Date.now()}-${file.name}`; await me.puter.fs.write(fileName, file); return { uploaded: true, fileName, originalName: file.name, size: file.size, }; }); // 404 handler router.get("/*tag", async ({ params }) => { return new Response( JSON.stringify({ error: "Not found", path: params.tag, availableEndpoints: ["/health", "/api/users", "/api/files/upload"], }), { status: 404, headers: { "Content-Type": "application/json" }, } ); }); ``` -------------------------------- ### Example: Using puter.ui.showDirectoryPicker() in HTML Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/showDirectoryPicker.md This example demonstrates how to trigger the directory picker via a button click and display the contents of the selected directory. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <button id="open-directory">Open directory</button> <h1 id="directory-name"></h1> <pre><code id="directory-content"></code></pre> <script> document.getElementById('open-directory').addEventListener('click', ()=>{ puter.ui.showDirectoryPicker().then(async (directory)=>{ // print directory name document.getElementById('directory-name').innerHTML = directory.name; // print directory content const children = await directory.readdir(); if(children.length){ let content = ''; for(let child of children){ content += child.name + '\n'; } document.getElementById('directory-content').innerText = content; }else{ document.getElementById('directory-content').innerText = 'Empty directory'; } }); }); </script> </body> </html> ``` -------------------------------- ### Connect to a server with TLS and print the response Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Networking/TLSSocket.md This HTML example creates a TLS socket to example.com:443, writes an HTTP GET request on open, decodes and prints incoming data, and handles errors and close events. It uses the Puter.js library and the puter.print function. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> const socket = new puter.net.tls.TLSSocket("example.com", 443); socket.on("tlsopen", () => { socket.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"); }) const decoder = new TextDecoder(); socket.on("tlsdata", (data) => { puter.print(decoder.decode(data), { code: true }); }) socket.on("error", (error) => { puter.print("Socket errored with the following reason: ", error.message); }) socket.on("tlsclose", (hadError)=> { puter.print("Socket closed. Was there an error? ", hadError); }) </script> </body> </html> ``` -------------------------------- ### Example: Fetch and print AI providers Source: https://github.com/heyputer/puter/blob/main/src/docs/src/AI/listModelProviders.md Complete HTML example that loads Puter.js from the CDN, calls puter.ai.listModelProviders() inside an async IIFE, and prints the resulting array of provider strings using puter.print(). ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // Fetch all providers const providers = await puter.ai.listModelProviders(); puter.print(providers) })(); </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> ``` -------------------------------- ### Example: HTML page with puter.ui.hideWindow() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/hideWindow.md Complete HTML example that includes the Puter script and calls hideWindow() to hide the window. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ui.hideWindow(); </script> </body> </html> ``` -------------------------------- ### Example usage of puter.auth.isSignedIn() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Auth/isSignedIn.md An example showing how to check the sign-in status and print the result using the Puter SDK in an HTML document. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print(`Sign in status: ${puter.auth.isSignedIn()}`); </script> </body> </html> ``` -------------------------------- ### Example response: listEngines() JSON Source: https://github.com/heyputer/puter/blob/main/src/docs/src/AI/txt2speech.listEngines.md Example JSON response showing an array of TTSEngine objects with id, name, provider, and optional pricing_per_million_chars. ```json [ { "id": "gpt-4o-mini-tts", "name": "GPT-4o Mini TTS", "provider": "openai", "pricing_per_million_chars": 12 }, { "id": "tts-1", "name": "TTS-1", "provider": "openai" } ] ``` -------------------------------- ### Start Puter with the ai profile Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Start the stack with the ai profile and monitor the ollama-init service. The ollama-init service exits 0 once the model is pulled; subsequent boots are fast no-ops. ```bash docker compose --profile ai up -d docker compose logs -f ollama-init ``` -------------------------------- ### 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" ] } ] } ``` -------------------------------- ### Create a simple website displaying "Hello world!" Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/create.md Creates a random directory, writes an index.html file with 'Hello, world!', hosts it under a random subdomain, and prints the hosted URL. ```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> ``` -------------------------------- ### 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" } } } ``` -------------------------------- ### Create an app pointing to example.com Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/create.md This example demonstrates creating an app with a random name, printing its UID, and then deleting it for cleanup. ```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> ``` -------------------------------- ### 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(); ``` -------------------------------- ### 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); }) ``` -------------------------------- ### Get the max key size Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/MAX_KEY_SIZE.md Example demonstrating how to print the maximum key size to the console using the Puter SDK. ```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> ``` -------------------------------- ### Launch an application Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/launchApp.md A basic example demonstrating how to launch the Editor app. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> // launches the Editor app puter.ui.launchApp('editor'); </script> </body> </html> ``` -------------------------------- ### Get the max value size Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/MAX_VALUE_SIZE.md HTML example that loads the Puter.js library and prints the maximum value size to the page. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("Max Value Size: " + puter.kv.MAX_VALUE_SIZE); </script> </body> </html> ``` -------------------------------- ### Get the ID of the current application Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/appID.md An example showing how to print the current application's ID using the Puter JavaScript SDK. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("App ID: " + puter.appID); </script> </body> </html> ``` -------------------------------- ### Complete Example: Deploy and Test a Worker Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/create.md A complete HTML example that writes a worker file to your Puter account, deploys it using puter.workers.create(), and tests it with a fetch request after a 5-second delay. The deployment may take up to 10 seconds. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // 1. Create a worker file in your Puter account. puter.print('β Writing the worker code to my-worker.js<br>'); const workerCode = ` // A router for /api/hello router.get('/api/hello', async (event) => { return 'Hello from worker!'; }); `; // Save the worker code to my-worker.js in your Puter account await puter.fs.write('my-worker.js', workerCode); // 2. Deploy the worker using the file path const workerName = puter.randName(); puter.print(`β Deploying ${workerName} worker. May take up to 10 seconds to deploy.<br>`); const deployment = await puter.workers.create(workerName, 'my-worker.js'); // 3. Test the worker puter.print(`β Wait 5 seconds before testing the worker to make sure it's propagated.<br>`); setTimeout(async ()=>{ const response = await fetch(`${deployment.url}/api/hello`); puter.print('β Test response: ', await response.text()); }, 5000); })(); </script> </body> </html> ``` -------------------------------- ### 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" } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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" } ``` -------------------------------- ### Example: Show feedback dialog on button click Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/showFeedbackDialog.md This HTML example includes the Puter script and attaches a click handler to a button. It calls showFeedbackDialog and prints a thank-you message if the user submits feedback. ```html <html> <body> <button id="feedback">Send us feedback</button> <script src="https://js.puter.com/v2/"></script> <script> document.getElementById('feedback').addEventListener('click', async () => { const sent = await puter.ui.showFeedbackDialog(); if (sent) { puter.print('Thanks for your feedback!'); } }); </script> </body> </html> ``` -------------------------------- ### 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 ``` -------------------------------- ### Upload a local file using fs_start_upload Source: https://github.com/heyputer/puter/blob/main/src/mcp-connector/README.md This workflow demonstrates how to upload a file by obtaining a presigned URL, executing the upload command, and finalizing the process. The size must match the file's exact byte count, and the Content-Type must match the signed value. ```text fs_start_upload({ path: "~/uploads/build.zip", size: 48210433, local_path: "./build.zip" }) -> { upload_id, url, upload_command, expires_at, ... } # run the returned upload_command: curl -sS --fail-with-body -X PUT -H 'Content-Type: application/zip' \ --upload-file './build.zip' 'https://...' fs_complete_upload({ upload_id }) -> the created file entry ``` -------------------------------- ### One-line installer for Puter Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Downloads and runs the installer script from the official repository. It generates secrets, writes configuration files, and starts services with docker compose up -d. Safe to re-run as it preserves existing configuration; use PUTER_FORCE=1 to force rotation of secrets. ```bash curl -fsSL https://raw.githubusercontent.com/HeyPuter/puter/main/install.sh | sh ``` -------------------------------- ### Deploy a whole set from a build step Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Events/handlers.md This example shows how to publish multiple handlers at once using puter.events.handlers.publishAll. It creates an app and publishes an array of handler definitions, then prints the outcome for each. Useful for deploying a set of handlers from a build step. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const name = `pipeline-${puter.randName()}`; const app = await puter.apps.create(name, `https://example.com/${name}`); const published = await puter.events.handlers.publishAll([ { name: 'ingestUpload', handler: ({ event, ctx }) => fetch(ctx.ingest, { body: event.path }), }, { name: 'indexDocument', handler: ({ event, ctx }) => fetch(ctx.index, { body: event.uid }), }, ], { appUid: app.uid }); for (const handler of published) { puter.print(`${handler.name} β ${handler.outcome}<br>`); } })(); </script> </body> </html> ``` -------------------------------- ### Basic and options syntax for puter.peer.serve() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/serve.md Shows the two valid call signatures: without options and with an options object. Use the options overload to pass settings like iceServers, forceRelay, anonToken, name, or guestGrant. ```javascript const server = await puter.peer.serve(); const server = await puter.peer.serve(options); ``` -------------------------------- ### Set and get a key-value pair with puter.kv Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/kv-get.html Uses the Puter.js KV store to set a key-value pair and then retrieve it. The example writes the result to the document and demonstrates the async/await pattern for both operations. ```javascript (async () => { // (1) Create a new key-value pair await puter.kv.set('name', 'Puter Smith'); document.write("Key-value pair 'name' created/updated<br>"); // (2) Retrieve the value of key 'name' const name = await puter.kv.get('name'); document.write('Name is: ' + name); })(); ``` -------------------------------- ### Complete HTML example using puter.ui.onLaunchedWithItems() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/onLaunchedWithItems.md A full HTML page that includes the Puter.js script and calls puter.ui.onLaunchedWithItems() to display the items array as JSON in the document body. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ui.onLaunchedWithItems(function(items){ document.body.innerHTML = JSON.stringify(items); }) </script> </body> </html> ``` -------------------------------- ### Example: Get the environment in which Puter.js is running Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/env.md HTML page that loads Puter.js and prints the environment using `puter.print`. The output is a string like 'app', 'web', 'gui', 'nodejs', 'web-worker', or 'service-worker'. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.print("Environment: " + puter.env); </script> </body> </html> ``` -------------------------------- ### Get wildcard TLS certificate with Certbot DNS-01 Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Use this Certbot command to obtain a wildcard certificate covering all required subdomains via DNS-01 challenge. This is recommended for public installs where users type passwords. ```bash sudo certbot certonly --manual --preferred-challenges dns \ -d puter.localhost -d "*.puter.localhost" \ -d site.puter.localhost -d "*.site.puter.localhost" \ -d host.puter.localhost -d "*.host.puter.localhost" \ -d app.puter.localhost -d "*.app.puter.localhost" \ -d dev.puter.localhost -d "*.dev.puter.localhost" ``` -------------------------------- ### Healthy Puter Startup Log Output Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Example output from a healthy startup of the puter container, showing config override, MySQL migrations applied. ```text [config] override from /etc/puter/config.json [mysql] running migrations from /opt/puter/dist/src/backend/clients/database/migrations/mysql: 2 file(s) [mysql] applied mysql_mig_1.sql (...) [mysql] applied mysql_mig_2.sql (9 statements) ``` -------------------------------- ### 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); })(); ``` -------------------------------- ### 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> ``` -------------------------------- ### 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> ``` -------------------------------- ### Stream subscriptions and filter suspended ones Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Events/list.md Uses puter.events.list({ stream: true }) to get an async iterator of page envelopes. Iterates over each page and prints the subject and suspendedReason for subscriptions that are suspended. Prints 'done' after the loop. This example demonstrates how to handle pagination with the stream option. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { for await (const page of puter.events.list({ stream: true })) { for (const row of page.items) { if (!row.suspendedAt) continue; puter.print(`${row.subject} stopped: ${row.suspendedReason}<br>`); } } puter.print('done<br>'); })(); </script> </body> </html> ``` -------------------------------- ### Example: Fetch all models with puter.ai.listModels() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/AI/listModels.md HTML page that loads the Puter.js library and calls puter.ai.listModels() to fetch all models, printing the first model to the console. ```html <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { // Fetch all models const models = await puter.ai.listModels(); puter.print('First model:', JSON.stringify(models[0])); })(); </script> </body> </html> ``` -------------------------------- ### Serving under a room name with puter.peer.serve() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/serve.md Creates a peer server bound to a custom room name instead of a generated invite code. The returned server's inviteCode equals the provided name. Names must be 3β64 characters of lowercase letters, digits, and hyphens, not starting or ending with a hyphen. The same name can be re-served by the same identity, but another identity gets a name_in_use error. ```javascript const server = await puter.peer.serve({ name: 'friday-standup' }); server.inviteCode; // 'friday-standup' ``` -------------------------------- ### Install @heyputer/cli Source: https://github.com/heyputer/puter/blob/main/src/cli/README.md Installs the Puter CLI globally. Requires Node 18+. ```sh npm install -g @heyputer/cli ``` -------------------------------- ### Install Build Essentials: Alpine Source: https://github.com/heyputer/puter/wiki/self_hosters-first_run_issues Command to install build-base on Alpine Linux. ```bash sudo apk add build-base ``` -------------------------------- ### Install Build Essentials: Debian-based Source: https://github.com/heyputer/puter/wiki/self_hosters-first_run_issues Commands to install build dependencies on Debian-based distributions. ```bash sudo apt update sudo apt install build-essential ``` -------------------------------- ### Install Nodemailer Source: https://github.com/heyputer/puter/wiki/contributors-email_testing Install the Nodemailer package to send test emails to the MailHog SMTP server. ```bash npm install nodemailer ```