### Basic Puter.js Usage: AI Chat Example Source: https://docs.puter.com/getting-started Demonstrates basic Puter.js usage by calling the `puter.ai.chat` function to interact with GPT-5 nano. This example includes the Puter.js script and a script block to show how to make the call and print the result, highlighting the library's no-backend, no-API-key approach. ```html ``` -------------------------------- ### Install Puter.js via Script Tag Source: https://docs.puter.com/getting-started This code snippet shows how to include the Puter.js library in your HTML file using a script tag. It's the first step to start using Puter.js, requiring no additional dependencies or configurations. ```html ``` -------------------------------- ### Get App Example with Puter.js Source: https://docs.puter.com/Apps/get This example demonstrates how to create a new app, retrieve it using `puter.apps.get()`, and then clean up by deleting the app. It utilizes asynchronous operations and the Puter.js library. ```javascript ``` -------------------------------- ### Website Hosting: Create, Get, Delete with Puter.js Source: https://docs.puter.com/playground_example=hosting-get This example demonstrates the basic workflow of hosting a website using Puter.js. It covers creating a new website with a random subdomain, retrieving its details, and then cleaning up by deleting the website. It assumes the Puter.js library is loaded via a script tag. ```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)
`); // (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}
`); // (3) Delete the website (cleanup) await puter.hosting.delete(subdomain); })(); ``` -------------------------------- ### Create, Delete, and Get App Example (JavaScript) Source: https://docs.puter.com/playground_example=app-delete Demonstrates the lifecycle of an application within the Puter.js environment. It includes creating a new app with a specified URL, deleting it, and then attempting to retrieve it to verify deletion. This example requires the Puter.js library to be included via a script tag. ```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
`); } })(); ``` -------------------------------- ### GET /hosting/get Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-get Retrieves information about a specific website using its subdomain. ```APIDOC ## GET /hosting/get ### Description Retrieves information about a specific website using its subdomain. ### Method GET ### Endpoint /hosting/get ### Parameters #### Query Parameters - **subdomain** (string) - Required - The subdomain of the website to retrieve. ### Request Example ```json { "subdomain": "my-random-website.puter.site" } ``` ### Response #### Success Response (200) - **subdomain** (string) - The subdomain of the website. - **uid** (string) - The unique identifier for the website. #### Response Example ```json { "subdomain": "my-random-website.puter.site", "uid": "some-unique-uid" } ``` ``` -------------------------------- ### Fetch data from a URL using Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=net-fetch This example demonstrates how to perform an HTTP GET request to a specified URL using the `puter.net.fetch` function. It retrieves the response body as text and then prints it to the console or output area with code formatting. No external dependencies are required beyond the Puter.js library. ```javascript ``` -------------------------------- ### GET /hosting/get Source: https://docs.puter.com/playground_example=hosting-get Retrieves information about a website using its subdomain. Returns website metadata including the subdomain, UID, and other properties. ```APIDOC ## GET /hosting/get ### Description Retrieves information about a website using its subdomain. Returns website metadata including the subdomain, UID, and other properties. ### Method GET ### Endpoint /hosting/get ### Parameters #### Path Parameters None #### Query Parameters - **subdomain** (string) - Required - The subdomain of the website to retrieve #### Request Body None ### Request Example GET /hosting/get?subdomain=my-awesome-site ### Response #### Success Response (200) - **subdomain** (string) - The subdomain of the website - **uid** (string) - Unique identifier for the website - **created** (string) - ISO timestamp of when the website was created - **modified** (string) - ISO timestamp of when the website was last modified #### Response Example { "subdomain": "my-awesome-site", "uid": "abc123-def456-ghi789", "created": "2024-01-15T10:30:00Z", "modified": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Set and Get User Preferences with Puter Key-Value Store Source: https://docs.puter.com/playground/index_autorun=1&example=intro-kv-set Demonstrates how to use Puter's key-value storage to save and retrieve user preferences. This example sets a user preference for dark mode and then retrieves it for display. Requires the Puter.js library to be loaded. ```javascript ``` -------------------------------- ### Host a static website with Puter.js Source: https://docs.puter.com/playground_example=hosting-create This example demonstrates how to create a directory, write an HTML file to it, and then host that directory as a static website using a random subdomain. It utilizes Puter.js's file system and hosting functionalities. ```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`, '

Hello, world!

'); // (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: https://${site.subdomain}.puter.site`); })(); ``` -------------------------------- ### Create and Use a Basic TCP Socket with Puter.js Source: https://docs.puter.com/playground_example=net-basic This example demonstrates how to create a basic TCP socket connection to a specified host and port using Puter.js. It sends an HTTP GET request and prints the received data, handles errors, and logs connection closure. Dependencies include the Puter.js library. ```html ``` -------------------------------- ### Create Website with Directory and Cleanup using Puter.js Source: https://docs.puter.com/playground_example=hosting-update This example demonstrates how to create a random website, generate a directory, update the website to use that directory, and perform cleanup by deleting the website. Requires the Puter.js library loaded from CDN. Uses async/await for handling asynchronous operations. ```javascript ``` -------------------------------- ### Create, Retrieve, and Delete a Website with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-get This example demonstrates how to create a new website, retrieve its details, and then delete it using the Puter.js hosting module. It requires the Puter.js SDK to be included via a script tag. The output includes the website's subdomain and UID. ```javascript ``` -------------------------------- ### Create, Update, and Delete an App with Puter.js Source: https://docs.puter.com/playground_example=app-update This example demonstrates the basic lifecycle of an application within Puter.js. It shows how to create a new app, update its title, and then clean up by deleting it. This requires the Puter.js library to be loaded. ```javascript ``` -------------------------------- ### Deploy and Test a Puter Worker Source: https://docs.puter.com/playground/index_autorun=1&example=workers-create This example demonstrates how to write worker code to a file, deploy it as a Puter worker, and then test its API endpoint. It requires the Puter.js SDK and an active Puter account. ```javascript ``` -------------------------------- ### Create and Delete a Random App with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=app-create This example demonstrates how to create a new random application using Puter.js, specify its target URL, and then clean up by deleting the created app. It requires the Puter.js library to be included. ```javascript ``` -------------------------------- ### Chat with Gemini AI Models Source: https://docs.puter.com/playground_example=ai-chat-gemini Demonstrates how to use Puter.js to chat with different Gemini AI models. The example compares responses from gemini-2.0-flash and gemini-1.5-flash models. Responses are streamed and displayed in the browser. ```javascript ``` -------------------------------- ### Puter.js: File System Operations (Write, Mkdir, Copy) Source: https://docs.puter.com/playground/index_autorun=1&example=fs-copy This example demonstrates basic file system operations using Puter.js. It shows how to write a text file, create a new directory, and copy the created file into the directory. The code utilizes `puter.fs.write`, `puter.fs.mkdir`, and `puter.fs.copy` methods. Errors during the copy operation are handled and reported. ```javascript ``` -------------------------------- ### Text to Speech with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=ai-txt2speech This example demonstrates how to convert text into speech using the Puter.js library. It includes an event listener for a button click to trigger the text-to-speech conversion and play the resulting audio. Dependencies include the Puter.js library, which is loaded via a script tag. ```html ``` -------------------------------- ### GET /apps/list Source: https://docs.puter.com/playground/index_autorun=1&example=app-update Lists all created apps. ```APIDOC ## GET /apps/list ### Description Lists all created applications. ### Method GET ### Endpoint /apps/list ### Parameters #### Path Parameters #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - `apps` (array) - An array of application objects. #### Response Example { "apps": [ { "appName": "MyTestApp", "title": "My Updated Test App!" } ] } ``` -------------------------------- ### Puter.js File System Operations: Create, Move, Delete Source: https://docs.puter.com/playground/index_autorun=1&example=fs-move This example demonstrates basic file system operations using Puter.js. It shows how to create a random text file, create a directory, move the file into the directory, and then clean up by deleting both the file and the directory. It utilizes functions like `puter.randName()`, `puter.fs.write()`, `puter.fs.mkdir()`, `puter.fs.move()`, and `puter.fs.delete()`. ```javascript ``` -------------------------------- ### DELETE /hosting/delete Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-get Deletes a website using its subdomain. This action is irreversible. ```APIDOC ## DELETE /hosting/delete ### Description Deletes a website using its subdomain. This action is irreversible. ### Method DELETE ### Endpoint /hosting/delete ### Parameters #### Query Parameters - **subdomain** (string) - Required - The subdomain of the website to delete. ### Request Example ```json { "subdomain": "my-random-website.puter.site" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message that the website was deleted. #### Response Example ```json { "message": "Website deleted successfully." } ``` ``` -------------------------------- ### Create a Simple Website (HTML/JavaScript) Source: https://docs.puter.com/playground_example=ai-txt2img-image-to-image Creates a basic HTML page that displays 'Hello world!'. This snippet uses standard HTML and JavaScript, likely intended for demonstration purposes within the Puter environment. No external dependencies are noted. ```html ``` -------------------------------- ### Create a simple 'Hello world!' website with Puter.js Hosting Source: https://docs.puter.com/Hosting This snippet demonstrates how to create a basic 'Hello world!' website. It first creates a directory and an 'index.html' file within it, then hosts this directory under a random subdomain using the Puter.js Hosting API. The output is the URL of the hosted website. ```javascript ``` -------------------------------- ### POST /hosting/create Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-get Creates a new random website and hosts it. The website will be empty initially. ```APIDOC ## POST /hosting/create ### Description Creates a new random website and hosts it. The website will be empty initially. ### Method POST ### Endpoint /hosting/create ### Parameters #### Query Parameters - **subdomain** (string) - Required - A unique name for the subdomain of the website. ### Request Example ```json { "subdomain": "my-random-website" } ``` ### Response #### Success Response (200) - **subdomain** (string) - The subdomain where the website is hosted. - **uid** (string) - The unique identifier for the website. #### Response Example ```json { "subdomain": "my-random-website.puter.site", "uid": "some-unique-uid" } ``` ``` -------------------------------- ### Simple GET Endpoint with Puter.js Router Source: https://docs.puter.com/Workers Defines a basic GET endpoint using the Puter.js router. This example demonstrates how to set up a simple route that responds with a JSON message. It takes a `request` object as input and returns a JavaScript object that is automatically converted to JSON. ```javascript // Simple GET endpoint router.get("/api/hello", async ({ request }) => { return { message: "Hello, World!" }; }); ``` -------------------------------- ### Host a Static Website with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=intro-hosting This example demonstrates how to create a new directory, write an HTML file into it, and then host that directory as a static website using Puter.js. It utilizes file system and hosting modules. ```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`, '

Hello, world!

'); // (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: https://${site.subdomain}.puter.site`); })(); ``` -------------------------------- ### HTML Example: Launch Editor App Source: https://docs.puter.com/UI/launchApp Complete HTML implementation showing how to integrate Puter.js and launch the Editor app. Includes script tag initialization and function call with string argument. ```html ``` -------------------------------- ### Returning JSON Response Source: https://docs.puter.com/Workers/router Example of returning a simple JSON object from a GET endpoint. The framework automatically converts the object to a JSON response. ```javascript router.get("/api/simple", async ({ request }) => { return { status: "ok" }; // Automatically converted to JSON }); ``` -------------------------------- ### Create an app pointing to example.com using JavaScript Source: https://docs.puter.com/Apps/create This snippet shows how to generate a random app name, create the app with a target URL, display its UID, and then delete the app using the Puter SDK. It requires loading the Puter v2 script and runs in a browser environment. No external dependencies beyond the SDK. ```HTML ``` -------------------------------- ### GET /api/users/:id Source: https://docs.puter.com/Workers/router Retrieves user data by ID from KV storage. Includes a security check to ensure the ID starts with 'user_'. ```APIDOC ## GET /api/users/:id ### Description Fetches stored user data by user ID, with validation for security. ### Method GET ### Endpoint /api/users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The user ID to retrieve #### Query Parameters None #### Request Body None ### Request Example No body required. ### Response #### Success Response (200) - **userId** (string) - The retrieved user ID - **user** (object) - User data including email and name #### Response Example { "userId": "user_1696166400000", "user": { "email": "user@example.com", "name": "user123" } } #### Error Response (404) - **error** (string) - Error message if user not found #### Error Response Example (404) { "error": "User not found" } ``` -------------------------------- ### GET /files/read Source: https://docs.puter.com/playground_example=hosting-get Reads the contents of a file from the user's storage. Returns the file content as a string or binary data depending on the file type. ```APIDOC ## GET /files/read ### Description Reads the contents of a file from the user's storage. Returns the file content as a string or binary data depending on the file type. ### Method GET ### Endpoint /files/read ### Parameters #### Path Parameters None #### Query Parameters - **path** (string) - Required - Full path to the file to read #### Request Body None ### Request Example GET /files/read?path=/documents/myfile.txt ### Response #### Success Response (200) - **content** (string) - File contents as string - **size** (number) - Size of the file in bytes - **modified** (string) - Last modification timestamp #### Response Example { "content": "Hello, world! This is a sample text file.", "size": 45, "modified": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Manage Applications with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=app-list This example demonstrates how to create, list, and delete applications using the Puter.js library. It first generates three random application names, then creates corresponding applications pointing to 'https://example.com'. It proceeds to list all applications and prints their names, followed by cleaning up by deleting the initially created applications. Dependencies include the Puter.js library, typically included via a script tag. ```javascript (async () => { // (1) Generate 3 random app names let appName_1 = puter.randName(); let appName_2 = puter.randName(); let appName_3 = puter.randName(); // (2) Create 3 apps await puter.apps.create(appName_1, 'https://example.com'); await puter.apps.create(appName_2, 'https://example.com'); await puter.apps.create(appName_3, 'https://example.com'); // (3) Get all apps (list) let apps = await puter.apps.list(); // (4) Display the names of the apps puter.print(JSON.stringify(apps.map(app => app.name))); // (5) Delete the 3 apps we created earlier (cleanup) await puter.apps.delete(appName_1); await puter.apps.delete(appName_2); await puter.apps.delete(appName_3); })(); ``` -------------------------------- ### Get Puter.js Execution Environment Source: https://docs.puter.com/Utils/env This example demonstrates how to access the `puter.env` property to determine the current environment where Puter.js is running. It prints the environment string (e.g., 'app', 'web', 'gui') to the console. This requires the Puter.js v2 library to be included. ```html ``` -------------------------------- ### Create and Delete Website - Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-delete Demonstrates how to create a new website using Puter.js, print its subdomain, and then delete it. It also includes a check to verify that the website can no longer be retrieved after deletion. This requires the Puter.js library to be included. ```javascript ``` -------------------------------- ### Create and Retrieve File Information in Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=fs-stat Demonstrates creating a file and retrieving its metadata using Puter.js. Creates 'hello.txt' with sample content and displays file properties like name, path, size, and creation date. Requires Puter.js SDK loaded via script tag. ```javascript ``` -------------------------------- ### TLS Socket Communication with Puter.js Source: https://docs.puter.com/playground_example=net-tls Demonstrates establishing a TLS socket connection to a specified host and port, sending an HTTP GET request, and printing the received data. It includes event handlers for connection open, data reception, errors, and closure. ```javascript const socket = new puter.net.tls.TLSSocket("example.com", 443); socket.on("open", () => { socket.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"); }) const decoder = new TextDecoder(); socket.on("data", (data) => { puter.print(decoder.decode(data), { code: true }); }) socket.on("error", (reason) => { puter.print("Socket errored with the following reason: ", reason); }) socket.on("close", (hadError)=> { puter.print("Socket closed. Was there an error? ", hadError); }) ``` -------------------------------- ### Get a Subdomain using puter.hosting.get() in JavaScript Source: https://docs.puter.com/Hosting/get This example demonstrates how to use `puter.hosting.get()` to retrieve website hosting details. It first creates a random website, then retrieves its information, and finally cleans up by deleting the website. This function requires the Puter.js library to be included. ```javascript ``` -------------------------------- ### Create and manage a random website with Puter.js Source: https://docs.puter.com/playground/index_autorun=1&example=hosting-update The snippet uses the Puter.js SDK to generate a random subdomain, create website, create a random directory, update the website's root directory to the new folder, and finally delete the website. It requires loading the Puter.js library (https://js.puter.com/v2/) and runs in an async IIFE. The code assumes the Puter SDK is available globally as `puter`. ```JavaScript (async () => { // (1) Create a random website let subdomain = puter.randName(); site = await puter.hosting.create(subdomain) puter.print(`Website hosted at: ${site.subdomain}.puter.site
`); // (2) Create a random directory let dirName = puter.randName(); let dir = await puter.fs.mkdir(dirName) puter.print(`Created directory \"${dir.path}\"
`); // (3) Update the site with the new random directory puter.hosting.update(subdomain, dirName) puter.print(`Changed subdomain's root directory to \"${dir.path}\"
`); // (4) Delete the app (cleanup) await puter.host.delete(updatedSite.subdomain) })(); ``` -------------------------------- ### Get Current Language using puter.ui.getLanguage() in JavaScript Source: https://docs.puter.com/UI/getLanguage This snippet demonstrates how to retrieve the current language code from the Puter environment using the `puter.ui.getLanguage()` function. It shows usage with both Promise `.then()` and `async/await` syntax, and includes an example of listening for language change events. ```javascript ``` -------------------------------- ### POST /hosting/create Source: https://docs.puter.com/playground_example=hosting-get Creates a new website with a randomly generated subdomain or specified name. Returns website information including the subdomain and unique identifier. ```APIDOC ## POST /hosting/create ### Description Creates a new website with a randomly generated subdomain or specified name. Returns website information including the subdomain and unique identifier. ### Method POST ### Endpoint /hosting/create ### Parameters #### Path Parameters - **subdomain** (string) - Optional - Custom subdomain name for the website (if not provided, a random name is generated) #### Query Parameters None #### Request Body - **subdomain** (string) - Optional - Custom subdomain name for the website ### Request Example { "subdomain": "my-awesome-site" } ### Response #### Success Response (200) - **subdomain** (string) - The subdomain of the created website - **uid** (string) - Unique identifier for the website - **url** (string) - Full URL where the website is hosted #### Response Example { "subdomain": "my-awesome-site", "uid": "abc123-def456-ghi789", "url": "https://my-awesome-site.puter.site" } ``` -------------------------------- ### Create and Get App with Puter.js Source: https://docs.puter.com/Apps This example shows how to generate a random app name, create a new application using puter.apps.create(), and then retrieve its details using puter.apps.get(). The snippet concludes with deleting the created application for cleanup. It depends on the Puter.js library. ```html ``` -------------------------------- ### Set and Get Key-Value Pair using Puter.js KV Store Source: https://docs.puter.com/playground/index_autorun=1&example=kv-get Demonstrates how to store and retrieve data using the key-value store in Puter.js. It first sets a value for the key 'name' and then retrieves it to display on the page. This functionality is useful for simple data persistence. ```javascript ``` -------------------------------- ### Deploy and Test a Puter Worker with Full Example Source: https://docs.puter.com/Workers/create This comprehensive example shows how to create a worker from scratch within an HTML file. It first writes the worker code to a file (`my-worker.js`) in the Puter account using `puter.fs.write()`, then deploys it using `puter.workers.create()`. Finally, it includes a `setTimeout` to wait for propagation and tests the deployed worker's endpoint using `fetch`. This demonstrates the end-to-end workflow for creating and verifying a serverless worker. ```html ``` -------------------------------- ### Worker Endpoint Testing Source: https://docs.puter.com/Workers/router Demonstrates testing procedures for Puter worker endpoints using puter.workers.exec(). Shows both GET and POST request testing patterns with proper response handling and JSON parsing. Includes setup for worker URL configuration and response validation techniques. ```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); ``` -------------------------------- ### POST /auth/sign-in Source: https://docs.puter.com/playground_example=hosting-get Authenticates a user and creates a new session. Returns user information and session details upon successful authentication. ```APIDOC ## POST /auth/sign-in ### Description Authenticates a user and creates a new session. Returns user information and session details upon successful authentication. ### Method POST ### Endpoint /auth/sign-in ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - Username for authentication - **password** (string) - Required - Password for authentication ### Request Example { "username": "user@example.com", "password": "securepassword123" } ### Response #### Success Response (200) - **token** (string) - Authentication token for subsequent requests - **user** (object) - User object containing user details - **expires_at** (string) - Token expiration timestamp #### Response Example { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": "user123", "username": "user@example.com", "email": "user@example.com" }, "expires_at": "2024-01-15T12:30:00Z" } ``` -------------------------------- ### Get Key-Value Pair in Puter.js HTML Source: https://docs.puter.com/KV The puter.kv.get() method retrieves the value associated with a given key. It depends on the Puter.js library and takes a key string as input, returning the stored value or null if not found. This example first sets a value then retrieves it, demonstrating asynchronous execution. ```html ``` -------------------------------- ### Install Puter.js via npm Source: https://docs.puter.com/supported-platforms Installs the Puter.js package using npm for use in Node.js or bundler-based web projects. Requires npm installed on the system. ```Shell npm install @heyputer/puter.js ```