Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する

Get Started


This guide walks you through the initial setup, installation, and execution of a minimal application using the Blocklet SDK. By following these steps, you will quickly have a working example that demonstrates the SDK's core functionality within a Blocklet Server environment.

For a deeper dive into the SDK's configuration options and environment variables, refer to the Environment & Config section.

Prerequisites#

Before you begin, ensure you have the following installed:

  • Node.js: Version 16.x or newer.
  • npm or Yarn: A package manager for Node.js.
  • Blocklet Server: The Blocklet SDK is designed to be used within a Blocklet running on Blocklet Server. You'll need a running Blocklet Server instance to deploy and test your application effectively.
  • A Blocklet Project: You should have an existing Blocklet project (e.g., one created using Blocklet CLI) where you intend to integrate the SDK.

Installation#

To install the Blocklet SDK in your project, navigate to your project's root directory in your terminal and run:

npm install @blocklet/sdk
# or
yarn add @blocklet/sdk

This command adds @blocklet/sdk as a dependency to your package.json file.

Understanding Blocklet Environment Variables#

Blocklet applications rely heavily on a set of environment variables provided by the Blocklet Server at runtime. These variables contain critical information about the Blocklet itself, the Blocklet Server instance, and the runtime context. The Blocklet SDK automatically reads and utilizes these variables to configure its services.

Some of the essential environment variables include:

Environment Variable

Description

Example Value

BLOCKLET_APP_ID

The unique DID (Decentralized Identifier) of your Blocklet application.

z83K2M...

BLOCKLET_APP_NAME

The human-readable name of your Blocklet application.

My Awesome Blocklet

BLOCKLET_APP_DESCRIPTION

A brief description of your Blocklet application.

A decentralized social app.

BLOCKLET_APP_SK

The secret key of your Blocklet application's DID, used for signing requests.

sk123...

BLOCKLET_DID

The DID of the current Blocklet instance. For a root Blocklet, this is usually the same as BLOCKLET_APP_ID.

z83K2M...

BLOCKLET_MODE

The runtime mode of the Blocklet, typically production or development.

development

ABT_NODE_DID

The DID of the Blocklet Server hosting the Blocklet.

zNKp...

ABT_NODE_PK

The public key of the Blocklet Server's DID.

pk123...

ABT_NODE_PORT

The HTTP port of the Blocklet Server.

8080

ABT_NODE_SERVICE_PORT

The service port of the Blocklet Server.

40406

BLOCKLET_DATA_DIR

The directory where your Blocklet should store persistent data.

/mnt/blocklet/data

BLOCKLET_LOG_DIR

The directory for Blocklet log files.

/mnt/blocklet/logs

The Blocklet SDK includes an internal check that ensures these critical environment variables are present. If any are missing, the SDK will typically throw an error to prevent the application from running in an incomplete environment.

Your First Blocklet SDK Application#

Let's create a minimal Express.js application that uses the Blocklet SDK to access environment information and inject window.blocklet for frontend usage.

  1. Create a new file (e.g., app.js) in your Blocklet project:// app.js
    import express from 'express';
    import { env, middlewares } from '@blocklet/sdk';

    const app = express();
    const port = process.env.PORT || 3000; // Blocklet Server will assign a port

    // Use Blocklet SDK middleware to inject window.blocklet into HTML responses.
    // This middleware also handles signature verification for requests from Blocklet Server.
    app.use(middlewares.blocklet());

    app.get('/', (req, res) => {
    // Access environment variables provided by Blocklet Server via `env` object
    const appName = env.appName || 'Unknown App';
    const appId = env.appId || 'Unknown ID';
    const serverDid = env.serverDid || 'Unknown Server DID';

    res.send(`
    <!DOCTYPE html>
    <html>
    <head>
    <title>${appName}</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
    <h1>Welcome to ${appName}!</h1>
    <p>Your Blocklet App ID: <code>${appId}</code></p>
    <p>Blocklet Server DID: <code>${serverDid}</code></p>
    <div id="blocklet-info"></div>

    <script>
    // The 'middlewares.blocklet()' injects a global 'window.blocklet' object.
    // This object contains useful runtime information for your frontend.
    if (window.blocklet) {
    const infoDiv = document.getElementById('blocklet-info');
    infoDiv.innerHTML += '<p>Data from window.blocklet:</p>';
    infoDiv.innerHTML += '<ul>';
    infoDiv.innerHTML += '<li>App Name (frontend): ' + window.blocklet.appName + '</li>';
    infoDiv.innerHTML += '<li>App Version: ' + window.blocklet.version + '</li>';
    infoDiv.innerHTML += '<li>Blocklet Server Version: ' + window.blocklet.serverVersion + '</li>';
    infoDiv.innerHTML += '<li>Is Component: ' + window.blocklet.isComponent + '</li>';
    infoDiv.innerHTML += '</ul>';
    } else {
    document.getElementById('blocklet-info').innerHTML += '<p><code>window.blocklet</code> object not found.</p>';
    console.warn('window.blocklet object not found. Ensure the Blocklet SDK middlewares are configured correctly.');
    }
    </script>
    </body>
    </html>
    `);
    });

    // Start the server
    app.listen(port, () => {
    console.log(`Blocklet application listening on port ${port}`);
    console.log('To run this application, ensure it is deployed to a Blocklet Server.');
    });

    This example demonstrates:
    • Importing env and middlewares from @blocklet/sdk.
    • Using middlewares.blocklet() to automatically inject client-side Blocklet information (window.blocklet).
    • Accessing server-side environment variables via env.
    • Displaying both server-side and client-side (via window.blocklet) Blocklet information.
  2. Update package.json: Ensure your package.json has express and @blocklet/sdk as dependencies. Also, configure your start script to run app.js.{
    "name": "my-first-blocklet-app",
    "version": "0.1.0",
    "scripts": {
    "start": "node app.js",
    "dev": "node app.js"
    },
    "dependencies": {
    "@blocklet/sdk": "^1.16.45",
    "express": "^4.19.2"
    }
    }

    Note: The version numbers for @blocklet/sdk and express in the example are illustrative. Always use the latest compatible versions.
  3. Deploy and Run: To run this application, you need to deploy it to a Blocklet Server. Blocklet Server will automatically set up the necessary environment variables and manage the application's lifecycle. Once deployed and started on Blocklet Server, you can access your Blocklet via its assigned URL.
    You can also run it locally for development, but you'll need to manually set the required environment variables. For instance, using a .env file with a tool like dotenv:# .env (example values, replace with actual DIDs/keys)
    BLOCKLET_APP_ID="z83K2Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    BLOCKLET_APP_NAME="My Dev Blocklet"
    BLOCKLET_APP_DESCRIPTION="A Blocklet for development"
    BLOCKLET_APP_SK="sk123xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    BLOCKLET_DID="z83K2Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    BLOCKLET_MODE="development"
    ABT_NODE_DID="zNKpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    ABT_NODE_PK="pk123xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    ABT_NODE_PORT="8080"
    ABT_NODE_SERVICE_PORT="40406"
    BLOCKLET_DATA_DIR="./data"
    BLOCKLET_LOG_DIR="./logs"
    PORT="3000" # For local development, if you don't use Blocklet Server's port management

    Then, install dotenv (npm install dotenv) and add require('dotenv').config(); at the very top of your app.js file.

Error Handling#

The Blocklet SDK includes built-in global error handlers for uncaughtException and unhandledRejection. These handlers log the error message and then exit the process, ensuring that critical issues are not silently ignored and that the application restarts cleanly if managed by a process manager.

While the SDK handles global unhandled errors, it is good practice to implement robust error handling within your application logic to gracefully manage expected errors and provide a better user experience.

Next Steps#

You have successfully set up and run your first Blocklet SDK application. Now, you are ready to explore the powerful features offered by the SDK's core services.

Continue to the Core Services section to learn about authentication, notifications, and component interaction.