Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

An introduction to JavaScript SDK for CloudEvents

March 9, 2021
Lucas Holmquist
Related topics:
Node.jsKubernetesEvent-driven

    In today's world of serverless functions and microservices, events are everywhere. The problem is that they are described differently depending on the producer technology you use.

    Without a common standard, the burden is on developers to constantly relearn how to consume events. Not having a standard also makes it more difficult for authors of libraries and tooling to deliver event data across environments like SDKs. Recently, a new project was created to help with this effort.

    CloudEvents is a specification for describing event data in common formats to provide interoperability across services, platforms, and systems. In fact, Red Hat OpenShift Serverless Functions uses CloudEvents. For more information about this new developer feature, see Create your first serverless function with Red Hat OpenShift Serverless Functions.

    The CloudEvents specification

    The specification's goal isn’t to create yet another event format and try to force everyone to use it. Rather, we want to define common metadata for events and establish where this metadata should appear in the message being sent.

    It is a simple spec with simple goals. In fact, a CloudEvent requires only four pieces of metadata:

    • type describes what kind of event this might be (e.g., a “create” event).
    • specversion denotes the version of the spec used to create the CloudEvent.
    • source describes where the event came from.
    • id is a unique identifier that is useful for de-duping.

    There are other useful fields, like subject, which when combined with source can add a little more context to where the event originated.

    As I mentioned, the CloudEvents specification is only concerned with the common metadata listed above, and the location where this metadata is placed when sending the event.

    Currently, there are two event formats: Binary, which is the preferred format, and structured. Binary is recommended because it is additive. That is, the binary format only adds some headers to the HTTP request. If there is a middleware that doesn’t understand CloudEvents, it won’t break anything, but if that system is updated to support CloudEvents, it starts working.

    Structured formats are for those who don’t have any format currently defined and are looking for guidance on how things should be structured.

    Here is a quick example of what those two event formats might look like in raw HTTP:

    // Binary
    
    Post  /event HTTP/1.0
    Host: example.com
    Content-Type: application/json
    ce-specversion: 1.0
    ce-type: com.nodeshift.create
    ce-source: nodeshift.dev
    ce-id: 123456
    {
      "action": "createThing",
      "item": "2187"
    }
    
    
    // Structured
    
    Post  /event HTTP/1.0
    Host: example.com
    Content-Type: application/cloudevents+json
    
    {
      "specversion": "1.0"
      "type": "com.nodeshift.create"
      "source": "nodeshift.dev"
      "id": "123456"
      "data": {
        "action": "createThing",
        "item": "2187"
      }
    }
    
    

    JavaScript SDK for CloudEvents

    Of course, we don’t want to have to format these events manually. That is where the JavaScript SDK for CloudEvents comes in. There are three main goals that an SDK should accomplish:

    • Compose an event.
    • Encode an event for sending.
    • Decode an incoming event.

    Installing the JavaScript SDK is like using any other Node module:

    $ npm install cloudevents
    

    Now that we’ve seen what a CloudEvent is and how it is useful let's take a look at an example.

    Create a new CloudEvent

    First, we are going to create a new CloudEvent object:

    const { CloudEvent } = require('cloudevents');
    
    // Create a new CloudEvent
    const ce = new CloudEvent({
     type: 'com.cloudevent.fun',
     source: 'fun-with-cloud-events',
     data: { key: 'DATA' }
    });
    

    If we log this out with the object's built-in toJSON method, we might see something like this:

    console.log(ce.toJSON());
    
    {
     id: '...',
     type: 'com.cloudevent.fun',
     source: 'fun-with-cloud-events',
     specversion: '1.0',
     time: '...',
     data: { key: 'DATA' }
    }
    
    

    Sending the message

    Next, let's look at how to send this over HTTP using the binary format.

    First, we need to create our message in the binary format, which you can do easily with the HTTP.binary method. We will use the CloudEvent from the previous example:

      const message = HTTP.binary(ce);
      //const message = HTTP.structured(ce); // Showing just for completeness
    

    Again, if we log this out, it might look something like this:

     headers: {
       'content-type': 'application/json;',
       'ce-id': '...',
       'ce-type': 'com.cloudevent.fun',
       'ce-source': 'fun-with-cloud-events',
       'ce-specversion': '1.0',
       'ce-time': '...'
     },
     body: { key: 'DATA' }
    }
    

    Now that the message has been formatted properly, we can send it by using a library like Axios.

    Note that the CloudEvents SDK doesn’t handle sending messages; it only handles formatting the message headers and message body. This allows you to use any HTTP library you want to send the message.

    const axios = require('axios')
    
    axios({
     method: 'post',
     url: 'http://localhost:3000/cloudeventy',
     data: message.body,
     headers: message.headers
    }).then((response) => {
     console.log(response.data);
    });
    
    

    We are sending a POST request to the “cloudevent-y” REST endpoint. In this example, I have used a simple Express.js application, but you can use any framework you like.

    Receiving the message

    Once we have the message, we can use the HTTP.toEvent method to convert it back into a CloudEvent object.

    const express = require('express');
    const { HTTP } = require('cloudevents');
    
    const app = express();
    
    app.post('/cloudeventy', (req, res) => {
      const ce = HTTP.toEvent({
                      headers: req.headers, 
                      body: req.body
      });
     console.log(ce.toJSON());
     res.send({key: 'Event Received'});
    });
    
    

    Again, the log output looks similar to what we saw when we output the CloudEvent object:

    {
     id: '...',
     type: 'com.cloudevent.fun',
     source: 'fun-with-cloud-events',
     specversion: '1.0',
     time: '...',
     data: { key: 'DATA' }
    }
    

    Conclusion

    To learn more about the JavaScript SDK for CloudEvents, check out the GitHub project. For more information about the history, development, and design rationale behind the specification, see the CloudEvents Primer.

    Last updated: March 8, 2021

    Recent Posts

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.