### Install and Run Puter Locally Source: https://github.com/heyputer/puter/wiki/_Footer Clone the Puter repository, install dependencies, and start the development server. ```sh git clone https://github.com/HeyPuter/puter.git npm install npm run start ``` -------------------------------- ### Install and Run Locally Source: https://github.com/heyputer/puter/blob/main/src/mcp-connector/README.md Installs dependencies and starts the development server for the MCP connector. This command builds the project and then launches it using Wrangler. ```bash cd src/mcp-connector npm install npm run dev # builds, then wrangler dev — serves on http://localhost:8787 ``` -------------------------------- ### Clone and Start Puter Locally Source: https://github.com/heyputer/puter/blob/main/README.md Clone the Puter repository, install dependencies, and start the local development server. This command sequence is used for setting up Puter on a local machine for development purposes. ```bash git clone https://github.com/HeyPuter/puter cd puter npm install npm start ``` -------------------------------- ### Get a subdomain Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/get.md This example demonstrates how to create a website, retrieve its details using `puter.hosting.get()`, and then clean up by deleting the website. Ensure the Puter SDK is loaded before executing. ```html ``` -------------------------------- ### Create and Get an App Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/get.md This example demonstrates how to create a random app, retrieve its details using `puter.apps.get()`, and then clean up by deleting the app. Ensure the Puter JS SDK is included. ```html ``` -------------------------------- ### Example: Create an app pointing to example.com Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/create.md This example demonstrates how to create a new Puter app using `puter.apps.create()`, assign it a URL, and then clean up by deleting it. ```APIDOC ## Example: Create an app pointing to example.com Create an app pointing to example.com ```html;app-create ``` ``` -------------------------------- ### Create, Get, and Delete an App with Puter SDK Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/app-get.html This example shows how to create a new application, retrieve it using its name, and then delete it. Ensure you have the Puter SDK initialized before running this code. ```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
`); // (3) Retrieve the app using get() let app = await puter.apps.get(appName); puter.print(`"${appName}" retrieved using get(): id: ${app.uid}
`); // (4) Delete the app (cleanup) await puter.apps.delete(appName); })(); ``` -------------------------------- ### Create a 'hello-puter' Extension Source: https://github.com/heyputer/puter/wiki/contributors-extensions-README Register a GET endpoint and listen to events. This example demonstrates how to access actor information and modify event behavior. ```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: // "", or: // " acting on behalf of " 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; } }); ``` -------------------------------- ### Clone and Run Puter.js Docs Locally Source: https://github.com/heyputer/puter/blob/main/src/docs/README.md Use these commands to clone the Puter.js documentation repository, install dependencies, and start the local development server. ```bash git clone https://github.com/HeyPuter/docs cd docs npm install npm run dev ``` -------------------------------- ### Connect to a server and print the response Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Networking/Socket.md This example demonstrates connecting to a server, sending an HTTP GET request, and printing the received data. It also includes error and close event handling. ```html ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Run these commands from the src/puter-js directory to install Playwright and its required browser binaries. This is a one-time setup step. ```sh cd /path/to/puter/src/puter-js npm install npm run playwright:install ``` -------------------------------- ### Example: Serve Peer and Handle Connections Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/serve.md Demonstrates how to serve a peer, retrieve the invite code, and set up event listeners for new connections and messages. This example includes the necessary HTML and JavaScript to run in a browser. ```html ``` -------------------------------- ### Example: Client-side connection and communication Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Peer/connect.md This example demonstrates how to connect to a peer server from a website using an invite code, send a message upon connection, and listen for messages from the server. ```html ``` -------------------------------- ### Show Directory Picker Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/showDirectoryPicker.md This example demonstrates how to use `puter.ui.showDirectoryPicker()` to open a directory picker, display the selected directory's name, and list its contents. It requires including the Puter SDK script. ```html

``` -------------------------------- ### Start Puter Desktop Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Run this command from the monorepo root to start the Puter desktop application. It will print default login credentials on first launch. ```sh cd /path/to/puter npm start ``` -------------------------------- ### Complete Worker Deployment and Testing Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/create.md This example demonstrates the full lifecycle: writing worker code to a file, deploying the worker using puter.workers.create(), and then testing it after a short propagation delay. Ensure the worker code is saved to 'my-worker.js' before deployment. ```html ``` -------------------------------- ### Install Puter.js NPM Library Source: https://github.com/heyputer/puter/blob/main/src/docs/src/frameworks.md Install the Puter.js NPM library using npm. ```bash npm install @heyputer/puter.js ``` -------------------------------- ### Example: Requesting and Using Documents Write Access Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Perms/requestWriteDocuments.md This example demonstrates how to request write access to the Documents folder and then write a file to it. It includes basic error handling for denied access. ```html ``` -------------------------------- ### Puter-JS End-to-End Test Setup and Execution Source: https://github.com/heyputer/puter/blob/main/src/puter-js/tests/e2e/README.md This snippet shows the essential commands for setting up and running end-to-end tests. It includes one-time setup for environment variables and commands for running tests in headless, headed, and recording modes. ```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 ``` -------------------------------- ### Example: Sign Out User in HTML Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Auth/signOut.md This HTML example demonstrates how to include the Puter SDK and call the signOut() function within a script tag. ```html ``` -------------------------------- ### Start puter-js Dev Server Source: https://github.com/heyputer/puter/blob/main/src/puter-js/TESTING.md Execute this command from the src/puter-js directory to start the puter-js development server, which serves necessary files for testing on localhost:8080. ```sh cd /path/to/puter/src/puter-js npm start ``` -------------------------------- ### Start Puter with Docker Compose Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md Bring up the Puter application and its services using Docker Compose. This command starts all defined services in detached mode. ```bash docker compose up -d ``` -------------------------------- ### Create a simple website displaying "Hello world!" Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/create.md This example demonstrates how to create a random directory, write an 'index.html' file with "Hello, world!" content into it, and then host this directory under a random subdomain. It utilizes `puter.randName()`, `puter.fs.mkdir()`, `puter.fs.write()`, and `puter.hosting.create()`. ```html ``` -------------------------------- ### 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 a Puter app with a specified name and index URL. It includes cleanup by deleting the app after creation. Ensure the Puter SDK is loaded before executing. ```html ``` -------------------------------- ### Complete Worker Router Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/router.md This snippet shows a comprehensive worker setup with multiple endpoints for health checks, user management, file uploads, and a catch-all 404 handler. It demonstrates GET and POST requests, parameter extraction, KV and FS interactions, and custom response handling. ```javascript // 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" }, } ); }); ``` -------------------------------- ### Install Base Development Packages on Arch Linux Source: https://github.com/heyputer/puter/wiki/self_hosters-first_run_issues Install the 'base-devel' package group on Arch Linux to get the necessary build tools. ```bash sudo pacman -S base-devel ``` -------------------------------- ### Create and list websites Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/list.md This example demonstrates creating three random websites, listing them using `puter.hosting.list()`, displaying their subdomains, and then cleaning up by deleting the created sites. ```html ``` -------------------------------- ### Get a subdomain Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting.md This example shows how to retrieve information about a specific subdomain, including its UID. It first creates a website and then uses the get() method to fetch its details. ```APIDOC ## GET /hosting/get ### Description Retrieves information about a specific hosting deployment (subdomain). ### Method GET ### Endpoint /hosting/get ### Parameters #### Query Parameters - **subdomain** (string) - Required - The subdomain to retrieve information for. ### Response #### Success Response (200) - **subdomain** (string) - The subdomain name. - **uid** (string) - The unique identifier for the hosting deployment. ``` -------------------------------- ### One-line Installer for Puter Source: https://github.com/heyputer/puter/blob/main/doc/self-hosting.md This command downloads and executes the official Puter installation script. It automates the generation of secrets, configuration file setup, and Docker Compose deployment. ```bash curl -fsSL https://raw.githubusercontent.com/HeyPuter/puter/main/install.sh | sh ``` -------------------------------- ### Create a new file with 'Hello, world!' Source: https://github.com/heyputer/puter/blob/main/src/docs/src/FS/write.md Use this snippet to create a new text file with specific content. Ensure the Puter SDK is included. ```html ``` -------------------------------- ### Defining a Custom Puter Kernel Module Source: https://github.com/heyputer/puter/wiki/backend-contributors-modules Example of a custom module extending `AdvancedBase` and implementing the `install` method to register new services. The `install` method receives a `Context` object, which provides access to the services container. ```javascript class MyPuterModule extends AdvancedBase { async install (context) { const services = context.get('services'); const MyService = require('./path/to/MyService.js'); services.registerService('my-service', MyService, { some_options: 'for-my-service', }); } } ``` -------------------------------- ### Read File Example Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/fs-read.html Use `puter.fs.read` to get the content of a file as a Blob. Then, convert the Blob to text using `.text()`. ```javascript (async () => { // (1) Create a random text file let filename = puter.randName() + ".txt"; await puter.fs.write(filename, "Hello world! I'm a file!"); puter.print(`"${filename}" created
`); // (2) Read the file and print its contents let blob = await puter.fs.read(filename); let content = await blob.text(); puter.print(`"${filename}" read (content: "${content}")
`); })(); ``` -------------------------------- ### Get a Key-Value Pair Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV.md This example demonstrates how to retrieve the value associated with a specific key. It first sets a pair and then retrieves it. ```html ``` -------------------------------- ### Install and Run MailHog Source: https://github.com/heyputer/puter/wiki/contributors-email_testing Download the MailHog binary for Linux, make it executable, and run it to start the local SMTP server. ```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 ``` -------------------------------- ### List all apps Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/list.md This example demonstrates how to create three random apps, list them using `puter.apps.list()`, and then clean them up. Ensure the Puter SDK is included. ```html ``` -------------------------------- ### Get Puter.js Environment Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/env.md This example demonstrates how to retrieve and display the current Puter.js environment using the `puter.env` property within an HTML page. ```html ``` -------------------------------- ### Create and Delete a Website Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Hosting/delete.md This example demonstrates how to create a random website, then delete it using the `puter.hosting.delete()` method. It also shows how to verify deletion by attempting to retrieve the website, which should fail. ```html ``` -------------------------------- ### Bootstrapping Puter Kernel with Core Modules Source: https://github.com/heyputer/puter/wiki/backend-contributors-modules This snippet demonstrates how to initialize the Puter kernel and add essential modules for a self-hosted run. Ensure all required modules like CoreModule, DatabaseModule, and StorageModule are included before booting. ```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(); ``` -------------------------------- ### Use Wildcard Routes Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/router.md Example of defining a GET endpoint with a wildcard route. The wildcard `*path` captures the rest of the path and makes it available as `params.path`. ```javascript router.get("/files/*path", async ({ params }) => { // A request to /files/images/avatars/me.png gives: // params.path === "images/avatars/me.png" return { path: params.path }; }); ``` -------------------------------- ### Capture Route Parameters Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Workers/router.md Example of defining a GET endpoint with route parameters. Captured segments like `:category` and `:id` are available on the `params` object. ```javascript router.get("/api/posts/:category/:id", async ({ params }) => { const { category, id } = params; return { category, id }; }); ``` -------------------------------- ### Set, Delete, and Get Key-Value Pair Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/kv-del.html This example shows how to create a new key-value pair, then delete it, and finally attempt to retrieve it to confirm deletion. ```javascript (async () => { // create a new key-value pair await puter.kv.set('name', 'Puter Smith'); document.write("Key-value pair 'name' created/updated
"); // delete the key 'name' await puter.kv.del('name'); document.write("Key-value pair 'name' deleted
"); // try to retrieve the value of key 'name' const name = await puter.kv.get('name'); document.write('Name is now: ', name); })(); ``` -------------------------------- ### Get Application ID in HTML Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/appID.md Include the Puter SDK and use `puter.appID` to retrieve the application's ID. This example prints the ID to the console. ```html ``` -------------------------------- ### Example: Print "Hello, world!" Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/print.md Demonstrates how to print a simple string to the document. ```APIDOC ## Example: Print "Hello, world!" ```html ``` ``` -------------------------------- ### Get the max key size Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/MAX_KEY_SIZE.md This example demonstrates how to retrieve and display the maximum key size allowed by the key-value store using a simple HTML script. ```html ``` -------------------------------- ### Create and then delete an app Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/delete.md This example demonstrates creating a random app, printing its creation, deleting it, and then attempting to retrieve it to confirm deletion. Ensure the Puter SDK is loaded before executing. ```html ``` -------------------------------- ### Read a file Source: https://github.com/heyputer/puter/blob/main/src/docs/src/FS/read.md This example demonstrates how to create a text file, write content to it, and then read its content back using `puter.fs.read()`. Ensure the Puter SDK is included in your HTML. ```html ``` -------------------------------- ### AI Function Calling Source: https://github.com/heyputer/puter/blob/main/src/docs/src/AI/chat.md Enable the AI to call external functions by defining tools. This example demonstrates how to get weather information by calling a mock 'getWeather' function. ```html ``` -------------------------------- ### Get Max Value Size in HTML Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/MAX_VALUE_SIZE.md This example demonstrates how to retrieve and display the maximum value size for the key-value store within an HTML page using the puter.js SDK. ```html ``` -------------------------------- ### Full Production HTML Example for Puter Source: https://github.com/heyputer/puter/wiki/prod This HTML file includes the Puter GUI script and initializes it. It also sets up essential meta tags, favicons, and branding assets for a complete production deployment. ```html Puter ``` -------------------------------- ### puter.apps.create() Syntax Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Apps/create.md Demonstrates the different ways to invoke the `puter.apps.create` function, including variations with different parameters and an options object. ```APIDOC ## puter.apps.create() ### Description Creates a Puter app with the given name. The app will be created in the user's apps, and will be accessible to this app. The app will be created with no permissions, and will not be able to access any data until permissions are granted to it. ### Syntax ```js puter.apps.create(name, indexURL) puter.apps.create(name, indexURL, title) puter.apps.create(options) ``` ### Parameters #### `name` (required) The name of the app to create. This name must be unique to the user's apps. If an app with this name already exists, the promise will be rejected. #### `indexURL` (required) The URL of the app's index page. This URL must be accessible to the user. If this parameter is not provided, the app will be created with no index page. The index page is the page that will be displayed when the app is started. **IMPORTANT**: The URL _must_ start with either `http://` or `https://`. Any other protocols (including `file://`, `ftp://`, etc.) are not allowed and will result in an error. For example: ✅ `https://example.com/app/index.html`
✅ `http://localhost:3000/index.html`
❌ `file:///path/to/index.html`
❌ `ftp://example.com/index.html`
#### `title` (required) The title of the app. If this parameter is not provided, the app will be created with `name` as its title. #### `options` (required) An object containing the options for the app to create. The object can contain the following properties: - `name` (String) (required): The name of the app to create. This name must be unique to the user's apps. If an app with this name already exists, the promise will be rejected. - `indexURL` (String) (required): The URL of the app's index page. This URL must be accessible to the user. If this parameter is not provided, the app will be created with no index page. - `title` (String) (optional): The human-readable title of the app. If this parameter is not provided, the app will be created with `name` as its title. - `description` (String) (optional): The description of the app aimed at the end user. - `icon` (String) (optional): The new icon of the app. - `maximizeOnStart` (Boolean) (optional): Whether the app should be maximized when it is started. Defaults to `false`. - `filetypeAssociations` (Array) (optional): An array of strings representing the filetypes that the app can open. Defaults to `[]`. File extentions and MIME types are supported; For example, `[".txt", ".md", "application/pdf"]` would allow the app to open `.txt`, `.md`, and PDF files. - `dedupeName` (Boolean) (optional) - Whether to deduplicate the app name if it already exists. Defaults to `false`. - `background` (Boolean) (optional) - Whether the app should run in the background. Defaults to `false`. - `metadata` (Object) (optional) - An object containing custom metadata for the app. This can be used to store arbitrary key-value pairs associated with the app. ### Return value A `Promise` that will resolve to the [`CreateAppResult`](/Objects/createappresult/) object that was created. ``` -------------------------------- ### Basic HTML Structure with hideWindow() Source: https://github.com/heyputer/puter/blob/main/src/docs/src/UI/hideWindow.md An example demonstrating how to include the Puter SDK and hide the window within an HTML file. ```html ``` -------------------------------- ### Example: Print "Hello, world!" as code Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Utils/print.md Demonstrates how to print a string as code, wrapping it in `` and `
` tags.

```APIDOC
## Example: Print "Hello, world!" as code

```html

  
    
    
  

```
```

--------------------------------

### List keys matching a pattern

Source: https://github.com/heyputer/puter/blob/main/src/docs/src/KV/list.md

Provide a string pattern to filter keys. The pattern supports a wildcard '*' only at the end for prefix matching. For example, 'abc*' matches keys starting with 'abc'.

```javascript
puter.kv.list(pattern)
```

--------------------------------

### Get Paginated List of App Users

Source: https://github.com/heyputer/puter/blob/main/src/docs/src/Objects/app.md

Use the `getUsers()` method to retrieve a paginated list of users for an app. You can specify `limit` and `offset` to control the number of users and the starting point of the retrieval.

```html


    
    


```

--------------------------------

### Create and Delete an App

Source: https://github.com/heyputer/puter/blob/main/src/docs/src/playground/examples/app-delete.html

This example shows the full lifecycle of an app: creation, deletion, and then attempting to retrieve it to confirm deletion. It uses `puter.randName()` to ensure a unique name for the app before creation.

```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
`); // (3) Delete the app await puter.apps.delete(appName); puter.print(`"${appName}" deleted
`); // (4) Try to retrieve the app (should fail) puter.print(`Trying to retrieve "${appName}"...
`); try { await puter.apps.get(appName); } catch (e) { puter.print(`"${appName}" could not be retrieved
`); } })(); ```