This guide provides a minimal, step-by-step example to help you set up a basic DID Connect session in your Node.js application. By the end of this tutorial, you will have a working server that can request a user's profile information via their DID Wallet.
1. Installation
First, you need to install the necessary packages. This library is designed to work with web server frameworks like Express.js. You will also need a storage adapter to manage session tokens.
Install required packages
# Using npm
npm install express @arcblock/did-connect-js @arcblock/did-connect-storage-nedb @ocap/wallet
# Using pnpm
pnpm install express @arcblock/did-connect-js @arcblock/did-connect-storage-nedb @ocap/walletexpress: The web server framework.@arcblock/did-connect-js: The main library for handling DID Connect sessions.@arcblock/did-connect-storage-nedb: A simple file-based storage adapter for session tokens. Other adapters are also available.@ocap/wallet: A library to create and manage DID wallets, which we'll use to create an identity for our application.
2. Initializing the Server
Now, let's set up the core components for DID Connect in an index.js file. The two main classes you'll work with are WalletAuthenticator and WalletHandlers.
WalletAuthenticator: Manages your application's identity and is responsible for creating and signing authentication requests.WalletHandlers: Provides a set of Express.js middleware to handle the entire DID Connect session lifecycle.
Here's the initial setup:
index.js
const express = require('express');
const { fromRandom } = require('@ocap/wallet');
const SimpleStorage = require('@arcblock/did-connect-storage-nedb');
const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-connect-js');
// 1. Create a wallet for your application
// This wallet represents your application's identity.
// In a real application, you should persist and reuse this wallet.
const wallet = fromRandom();
// 2. Configure the WalletAuthenticator
const authenticator = new WalletAuthenticator({
wallet, // The application's wallet
baseUrl: 'http://localhost:3000', // Your application's public URL
appInfo: {
name: 'My First DID Connect App',
description: 'A simple app to demonstrate DID Connect.',
icon: 'https://arcblock.oss-cn-beijing.aliyuncs.com/images/wallet-round.png', // URL to your app's logo
},
chainInfo: {
host: 'https://babel.arcblock.io/api',
id: 'babel',
},
});
// 3. Configure the WalletHandlers
const handlers = new WalletHandlers({
authenticator,
tokenStorage: new SimpleStorage({ dbPath: './auth.db' }), // Storage for session tokens
});
// 4. Create an Express app
const app = express();
// This is required for dynamic baseUrl inference if not explicitly set
app.set('trust proxy', true);
// ... Attach handlers in the next step
// 5. Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
console.log(`Application DID: ${wallet.toAddress()}`);
});3. Handling the Connection
With the authenticator and handlers configured, the final step is to attach the DID Connect endpoints to your Express app. This is done using the handlers.attach() method, where you define the specific claims to request and the callback to execute upon successful authentication.
Add the following code to your index.js file before app.listen():
index.js
// Attach the DID Connect session handler
handlers.attach(app, {
// A unique name for this authentication action
action: 'profileLogin',
// Define the information you want to request from the user
claims: {
profile: () => ({
fields: ['fullName', 'email'],
description: 'Please provide your name and email to sign in.',
}),
},
// This callback is executed after the user approves the request in their wallet
onAuth: async ({ userDid, claims }) => {
// `userDid` is the DID of the connected user.
// `claims` is an array containing the information submitted by the user.
const profile = claims.find((x) => x.type === 'profile');
console.log('Login successful!');
console.log('User DID:', userDid);
console.log('User Profile:', profile);
},
});4. The Complete Code
Here is the complete, runnable code for your index.js file. You can save this and run it directly.
index.js
const express = require('express');
const { fromRandom } = require('@ocap/wallet');
const SimpleStorage = require('@arcblock/did-connect-storage-nedb');
const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-connect-js');
// 1. Create a wallet for your application
const wallet = fromRandom();
// 2. Configure the WalletAuthenticator
const authenticator = new WalletAuthenticator({
wallet,
baseUrl: 'http://localhost:3000',
appInfo: {
name: 'My First DID Connect App',
description: 'A simple app to demonstrate DID Connect.',
icon: 'https://arcblock.oss-cn-beijing.aliyuncs.com/images/wallet-round.png',
},
chainInfo: {
host: 'https://babel.arcblock.io/api',
id: 'babel',
},
});
// 3. Configure the WalletHandlers
const handlers = new WalletHandlers({
authenticator,
tokenStorage: new SimpleStorage({ dbPath: './auth.db' }),
});
// 4. Create an Express app and attach handlers
const app = express();
app.set('trust proxy', true);
handlers.attach(app, {
action: 'profileLogin',
claims: {
profile: () => ({
fields: ['fullName', 'email'],
description: 'Please provide your name and email to sign in.',
}),
},
onAuth: async ({ userDid, claims }) => {
const profile = claims.find((x) => x.type === 'profile');
console.log('Login successful!');
console.log('User DID:', userDid);
console.log('User Profile:', profile);
},
});
// 5. Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
console.log(`Application DID: ${wallet.toAddress()}`);
});Now, run the application:
node index.jsYour backend is now ready to handle a DID Connect session. To complete the flow, you'll need a frontend to display the QR code. For a quick test, you can use the DID Connect UX library or integrate it into your web application.
Next Steps
Congratulations! You've successfully set up a basic DID Connect server. Now you can explore more advanced features.