Server

Introduction

The Dapr Server will allow you to receive communication from the Dapr Sidecar and get access to its server facing features such as: Subscribing to Events, Receiving Input Bindings, and much more.

Pre-requisites

Installing and importing Dapr’s JS SDK

  1. Install the SDK with npm:
  1. npm i @dapr/dapr --save
  1. Import the libraries:
  1. import { DaprServer, CommunicationProtocolEnum } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server
  6. // HTTP Example
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. communicationProtocol: CommunicationProtocolEnum.HTTP, // DaprClient to use same communication protocol as DaprServer, in case DaprClient protocol not mentioned explicitly
  11. clientOptions: {
  12. daprHost,
  13. daprPort,
  14. },
  15. });
  16. // GRPC Example
  17. const server = new DaprServer({
  18. serverHost,
  19. serverPort,
  20. communicationProtocol: CommunicationProtocolEnum.GRPC,
  21. clientOptions: {
  22. daprHost,
  23. daprPort,
  24. },
  25. });

Running

To run the examples, you can use two different protocols to interact with the Dapr sidecar: HTTP (default) or gRPC.

Using HTTP (built-in express webserver)

  1. import { DaprServer } from "@dapr/dapr";
  2. const server = new DaprServer({
  3. serverHost: appHost,
  4. serverPort: appPort,
  5. clientOptions: {
  6. daprHost,
  7. daprPort,
  8. },
  9. });
  10. // initialize subscribtions, ... before server start
  11. // the dapr sidecar relies on these
  12. await server.start();
  1. # Using dapr run
  2. dapr run --app-id example-sdk --app-port 50051 --app-protocol http -- npm run start
  3. # or, using npm script
  4. npm run start:dapr-http

ℹ️ Note: The app-port is required here, as this is where our server will need to bind to. Dapr will check for the application to bind to this port, before finishing start-up.

Using HTTP (bring your own express webserver)

Instead of using the built-in web server for Dapr sidecar to application communication, you can also bring your own instance. This is helpful in scenarios like when you are building a REST API back-end and want to integrate Dapr directly in it.

Note, this is currently available for express only.

💡 Note: when using a custom web-server, the SDK will configure server properties like max body size, and add new routes to it. The routes are unique on their own to avoid any collisions with your application, but it’s not guaranteed to not collide.

  1. import { DaprServer, CommunicationProtocolEnum } from "@dapr/dapr";
  2. import express from "express";
  3. const myApp = express();
  4. myApp.get("/my-custom-endpoint", (req, res) => {
  5. res.send({ msg: "My own express app!" });
  6. });
  7. const daprServer = new DaprServer({
  8. serverHost: "127.0.0.1", // App Host
  9. serverPort: "50002", // App Port
  10. serverHttp: myApp,
  11. clientOptions: {
  12. daprHost
  13. daprPort
  14. }
  15. });
  16. // Initialize subscriptions before the server starts, the Dapr sidecar uses it.
  17. // This will also initialize the app server itself (removing the need for `app.listen` to be called).
  18. await daprServer.start();

After configuring the above, you can call your custom endpoint as you normally would:

  1. const res = await fetch(`http://127.0.0.1:50002/my-custom-endpoint`);
  2. const json = await res.json();

Using gRPC

Since HTTP is the default, you will have to adapt the communication protocol to use gRPC. You can do this by passing an extra argument to the client or server constructor.

  1. import { DaprServer, CommunicationProtocol } from "@dapr/dapr";
  2. const server = new DaprServer({
  3. serverHost: appHost,
  4. serverPort: appPort,
  5. communicationProtocol: CommunicationProtocolEnum.GRPC,
  6. clientOptions: {
  7. daprHost,
  8. daprPort,
  9. },
  10. });
  11. // initialize subscribtions, ... before server start
  12. // the dapr sidecar relies on these
  13. await server.start();
  1. # Using dapr run
  2. dapr run --app-id example-sdk --app-port 50051 --app-protocol grpc -- npm run start
  3. # or, using npm script
  4. npm run start:dapr-grpc

ℹ️ Note: The app-port is required here, as this is where our server will need to bind to. Dapr will check for the application to bind to this port, before finishing start-up.

Building blocks

The JavaScript Server SDK allows you to interface with all of the Dapr building blocks focusing on Sidecar to App features.

Invocation API

Listen to an Invocation

  1. import { DaprServer, DaprInvokerCallbackContent } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const callbackFunction = (data: DaprInvokerCallbackContent) => {
  16. console.log("Received body: ", data.body);
  17. console.log("Received metadata: ", data.metadata);
  18. console.log("Received query: ", data.query);
  19. console.log("Received headers: ", data.headers); // only available in HTTP
  20. };
  21. await server.invoker.listen("hello-world", callbackFunction, { method: HttpMethod.GET });
  22. // You can now invoke the service with your app id and method "hello-world"
  23. await server.start();
  24. }
  25. start().catch((e) => {
  26. console.error(e);
  27. process.exit(1);
  28. });

For a full guide on service invocation visit How-To: Invoke a service.

PubSub API

Subscribe to messages

Subscribing to messages can be done in several ways to offer flexibility of receiving messages on your topics:

  • Direct subscription through the subscribe method
  • Direct susbcription with options through the subscribeWithOptions method
  • Subscription afterwards through the susbcribeOnEvent method

Each time an event arrives, we pass its body as data and the headers as headers, which can contain properties of the event publisher (e.g., a device ID from IoT Hub)

Dapr requires subscriptions to be set up on startup, but in the JS SDK we allow event handlers to be added afterwards as well, providing you the flexibility of programming.

An example is provided below

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const pubSubName = "my-pubsub-name";
  16. const topic = "topic-a";
  17. // Configure Subscriber for a Topic
  18. // Method 1: Direct subscription through the `subscribe` method
  19. await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) =>
  20. console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`),
  21. );
  22. // Method 2: Direct susbcription with options through the `subscribeWithOptions` method
  23. await server.pubsub.subscribeWithOptions(pubSubName, topic, {
  24. callback: async (data: any, headers: object) =>
  25. console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`),
  26. });
  27. // Method 3: Subscription afterwards through the `susbcribeOnEvent` method
  28. // Note: we use default, since if no route was passed (empty options) we utilize "default" as the route name
  29. await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-1", {});
  30. server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "default", async (data: any, headers: object) => {
  31. console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`);
  32. });
  33. // Start the server
  34. await server.start();
  35. }

For a full list of state operations visit How-To: Publish & subscribe.

Subscribe with SUCCESS/RETRY/DROP status

Dapr supports status codes for retry logic to specify what should happen after a message gets processed.

⚠️ The JS SDK allows multiple callbacks on the same topic, we handle priority of status on RETRY > DROP > SUCCESS and default to SUCCESS

⚠️ Make sure to configure resiliency in your application to handle RETRY messages

In the JS SDK we support these messages through the DaprPubSubStatusEnum enum. To ensure Dapr will retry we configure a Resiliency policy as well.

components/resiliency.yaml

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Resiliency
  3. metadata:
  4. name: myresiliency
  5. spec:
  6. policies:
  7. retries:
  8. # Global Retry Policy for Inbound Component operations
  9. DefaultComponentInboundRetryPolicy:
  10. policy: constant
  11. duration: 500ms
  12. maxRetries: 10
  13. targets:
  14. components:
  15. messagebus:
  16. inbound:
  17. retry: DefaultComponentInboundRetryPolicy

src/index.ts

  1. import { DaprServer, DaprPubSubStatusEnum } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const pubSubName = "my-pubsub-name";
  16. const topic = "topic-a";
  17. // Process a message successfully
  18. await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
  19. return DaprPubSubStatusEnum.SUCCESS;
  20. });
  21. // Retry a message
  22. // Note: this example will keep on retrying to deliver the message
  23. // Note 2: each component can have their own retry configuration
  24. // e.g., https://docs.dapr.io/reference/components-reference/supported-pubsub/setup-redis-pubsub/
  25. await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
  26. return DaprPubSubStatusEnum.RETRY;
  27. });
  28. // Drop a message
  29. await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
  30. return DaprPubSubStatusEnum.DROP;
  31. });
  32. // Start the server
  33. await server.start();
  34. }

Subscribe to messages rule based

Dapr supports routing messages to different handlers (routes) based on rules.

E.g., you are writing an application that needs to handle messages depending on their “type” with Dapr, you can send them to different routes handlerType1 and handlerType2 with the default route being handlerDefault

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const pubSubName = "my-pubsub-name";
  16. const topic = "topic-a";
  17. // Configure Subscriber for a Topic with rule set
  18. // Note: the default route and match patterns are optional
  19. await server.pubsub.subscribe("pubsub-redis", "topic-1", {
  20. default: "/default",
  21. rules: [
  22. {
  23. match: `event.type == "my-type-1"`,
  24. path: "/type-1",
  25. },
  26. {
  27. match: `event.type == "my-type-2"`,
  28. path: "/type-2",
  29. },
  30. ],
  31. });
  32. // Add handlers for each route
  33. server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "default", async (data) => {
  34. console.log(`Handling Default`);
  35. });
  36. server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "type-1", async (data) => {
  37. console.log(`Handling Type 1`);
  38. });
  39. server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "type-2", async (data) => {
  40. console.log(`Handling Type 2`);
  41. });
  42. // Start the server
  43. await server.start();
  44. }

Susbcribe with Wildcards

The popular wildcards * and + are supported (make sure to validate if the pubsub component supports it) and can be subscribed to as follows:

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const pubSubName = "my-pubsub-name";
  16. // * Wildcard
  17. await server.pubsub.subscribe(pubSubName, "/events/*", async (data: any, headers: object) =>
  18. console.log(`Received Data: ${JSON.stringify(data)}`),
  19. );
  20. // + Wildcard
  21. await server.pubsub.subscribe(pubSubName, "/events/+/temperature", async (data: any, headers: object) =>
  22. console.log(`Received Data: ${JSON.stringify(data)}`),
  23. );
  24. // Start the server
  25. await server.start();
  26. }

Bulk Subscribe to messages

Bulk Subscription is supported and is available through following API:

  • Bulk subscription through the subscribeBulk method: maxMessagesCount and maxAwaitDurationMs are optional; and if not provided, default values for related components will be used.

While listening for messages, the application receives messages from Dapr in bulk. However, like regular subscribe, the callback function receives a single message at a time, and the user can choose to return a DaprPubSubStatusEnum value to acknowledge successfully, retry, or drop the message. The default behavior is to return a success response.

Please refer this document for more details.

  1. import { DaprServer } from "@dapr/dapr";
  2. const pubSubName = "orderPubSub";
  3. const topic = "topicbulk";
  4. const daprHost = process.env.DAPR_HOST || "127.0.0.1";
  5. const daprHttpPort = process.env.DAPR_HTTP_PORT || "3502";
  6. const serverHost = process.env.SERVER_HOST || "127.0.0.1";
  7. const serverPort = process.env.APP_PORT || 5001;
  8. async function start() {
  9. const server = new DaprServer({
  10. serverHost,
  11. serverPort,
  12. clientOptions: {
  13. daprHost,
  14. daprPort: daprHttpPort,
  15. },
  16. });
  17. // Publish multiple messages to a topic with default config.
  18. await client.pubsub.subscribeBulk(pubSubName, topic, (data) =>
  19. console.log("Subscriber received: " + JSON.stringify(data)),
  20. );
  21. // Publish multiple messages to a topic with specific maxMessagesCount and maxAwaitDurationMs.
  22. await client.pubsub.subscribeBulk(
  23. pubSubName,
  24. topic,
  25. (data) => {
  26. console.log("Subscriber received: " + JSON.stringify(data));
  27. return DaprPubSubStatusEnum.SUCCESS; // If App doesn't return anything, the default is SUCCESS. App can also return RETRY or DROP based on the incoming message.
  28. },
  29. {
  30. maxMessagesCount: 100,
  31. maxAwaitDurationMs: 40,
  32. },
  33. );
  34. }

Dead Letter Topics

Dapr supports dead letter topic. This means that when a message fails to be processed, it gets sent to a dead letter queue. E.g., when a message fails to be handled on /my-queue it will be sent to /my-queue-failed. E.g., when a message fails to be handled on /my-queue it will be sent to /my-queue-failed.

You can use the following options with subscribeWithOptions method:

  • deadletterTopic: Specify a deadletter topic name (note: if none is provided we create one named deadletter)
  • deadletterCallback: The method to trigger as handler for our deadletter

Implementing Deadletter support in the JS SDK can be done by either

  • Passing the deadletterCallback as an option
  • By subscribing to route manually with subscribeToRoute

An example is provided below

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server "
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const pubSubName = "my-pubsub-name";
  16. // Method 1 (direct subscribing through subscribeWithOptions)
  17. await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-5", {
  18. callback: async (data: any) => {
  19. throw new Error("Triggering Deadletter");
  20. },
  21. deadLetterCallback: async (data: any) => {
  22. console.log("Handling Deadletter message");
  23. },
  24. });
  25. // Method 2 (subscribe afterwards)
  26. await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-1", {
  27. deadletterTopic: "my-deadletter-topic",
  28. });
  29. server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "default", async () => {
  30. throw new Error("Triggering Deadletter");
  31. });
  32. server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "my-deadletter-topic", async () => {
  33. console.log("Handling Deadletter message");
  34. });
  35. // Start server
  36. await server.start();
  37. }

Bindings API

Receive an Input Binding

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. const serverHost = "127.0.0.1";
  5. const serverPort = "5051";
  6. async function start() {
  7. const server = new DaprServer({
  8. serverHost,
  9. serverPort,
  10. clientOptions: {
  11. daprHost,
  12. daprPort,
  13. },
  14. });
  15. const bindingName = "my-binding-name";
  16. const response = await server.binding.receive(bindingName, async (data: any) =>
  17. console.log(`Got Data: ${JSON.stringify(data)}`),
  18. );
  19. await server.start();
  20. }
  21. start().catch((e) => {
  22. console.error(e);
  23. process.exit(1);
  24. });

For a full guide on output bindings visit How-To: Use bindings.

Configuration API

💡 The configuration API is currently only available through gRPC

Getting a configuration value

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. const serverHost = "127.0.0.1";
  5. const serverPort = "5051";
  6. async function start() {
  7. const client = new DaprClient({
  8. daprHost,
  9. daprPort,
  10. communicationProtocol: CommunicationProtocolEnum.GRPC,
  11. });
  12. const config = await client.configuration.get("config-redis", ["myconfigkey1", "myconfigkey2"]);
  13. }
  14. start().catch((e) => {
  15. console.error(e);
  16. process.exit(1);
  17. });

Subscribing to Key Changes

  1. import { DaprServer } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. const serverHost = "127.0.0.1";
  5. const serverPort = "5051";
  6. async function start() {
  7. const client = new DaprClient({
  8. daprHost,
  9. daprPort,
  10. communicationProtocol: CommunicationProtocolEnum.GRPC,
  11. });
  12. const stream = await client.configuration.subscribeWithKeys("config-redis", ["myconfigkey1", "myconfigkey2"], () => {
  13. // Received a key update
  14. });
  15. // When you are ready to stop listening, call the following
  16. await stream.close();
  17. }
  18. start().catch((e) => {
  19. console.error(e);
  20. process.exit(1);
  21. });