Home Reference Source Test

cloudevent / cloudevent.js

NPM Version NPM Downloads Code Style Coverage Status dependencies Status devDependencies Status

JavaScript/Node.js implementation of CloudEvents

Current release implements the v0.2 of the CloudEvents Spec.

The purpose of this library is to create instances of CloudEvents in a simple way (with some useful defaults), or in a full way (all attributes). Optional, it's possible to validate created instances to be sure they are compliant with the standard.

Then, created instances can be serialized, for example to be sent (or saved/stored) somewhere.

Note that many features are exposed directly by the CloudEvent class with standard class instance methods, and even as class static methods (that operates on a given CloudEvent). Anyway, to be more future-proof the library now exports a main object, with all features inside (the class for CloudEvent, its Validator class as CloudEventValidator, etc); using destructuring assignment (as seen in code samples) usage will be easier.


Get a reference to the library:

// Node.js example

// reference the library, not needed if using destructuring assignment, see below
const CloudEventExports = require('cloudevent')

// minimal, most common usage
// const { CloudEvent } = require('cloudevent')
// other, get more objects exposed by the library
const { CloudEvent, CloudEventValidator: V, CloudEventTransformer: T } = require('cloudevent')
assert(CloudEvent !== null && V !== null && T !== null)

create some sample CloudEvent instances:

// create some sample instances but without mandatory fields (for validation) ...
const ceEmpty = new CloudEvent() // create an empty CloudEvent instance (not valid for the validator, even in default case, when strict mode flag is disabled)
const ceMinimalMandatoryUndefinedNoStrict = new CloudEvent(undefined, undefined, undefined, undefined, { strict: false }) // expected success
const ceMinimalMandatoryUndefinedStrict = new CloudEvent(undefined, undefined, undefined, undefined, { strict: true }) // expected failure, so ceMinimalMandatoryUndefinedStrict will not be defined

// define some common attributes
const ceCommonOptions = {
  time: new Date(),
  extensions: { 'exampleExtension': 'value' },
  contenttype: 'application/json',
  schemaurl: 'http://my-schema.localhost.localdomain/v1/',
  strict: false // same as default
const ceCommonOptionsStrict = { ...ceCommonOptions, strict: true }
const ceNamespace = 'com.github.smartiniOnGitHub.cloudeventjs.testevent-v1.0.0'
const ceServerUrl = '/test'
const ceCommonData = { 'hello': 'world', year: 2019 }

// create some sample minimal instances, good even for validation ...
const ceMinimal = new CloudEvent('1', // id
  ceNamespace, // type
  '/', // source
  {} // data (empty) // optional, but useful the same in this sample usage

// create some instances with an undefined mandatory argument (handled by defaults), but with strict flag disabled: expected success ...
// note that null values are not handled by default values, only undefined values ...
const ceFull = new CloudEvent('1/full',
  ceCommonData, // data
const ceFullStrict = new CloudEvent('2/full-strict',
  ceCommonData, // data
  ceCommonOptionsStrict // use common options, but set strict mode to true
assert(!ceFull.isStrict) // ensure common options object has not been changed when reusing some of its values for the second instance
assert(!CloudEvent.isStrictEvent(ceFull)) // the same, but using static method
// create an instance that wrap an Error
const error = new Error('sample error')
error.code = 1000 // add a sample error code, as number
const errorToData = T.errorToData(error, {
  includeStackTrace: true,
  // addStatus: false,
  addTimestamp: true
const ceErrorStrict = new CloudEvent('2/error-strict',
  errorToData, // data
  ceCommonOptionsStrict // use common options, but set strict mode to true
assert(ceErrorStrict !== null)
assert(!ceErrorStrict.isStrict) // ensure common options object has not been changed when reusing some of its values for the second instance
assert(!CloudEvent.isStrictEvent(ceErrorStrict)) // the same, but using static method
// create an instance with a different content type
const ceFullStrictOtherContentType = new CloudEvent('3/full-strict-other-content-type',
  ceCommonData, // data
  { ...ceCommonOptionsStrict, contenttype: 'application/xml' } // use common strict options, but set strict mode to true
assert(ceFullStrictOtherContentType !== null)

optional, do some validations/checks on created instances. As sample, use class static methods like 'isValidEvent' and 'ValidateEvent', or instance methods like 'isValid', 'validate', etc ...

// etc ...

console.log(`Validation on ceEmpty: isValid: ${ceEmpty.isValid()}, `)

console.log(`Validation output for ceEmpty, default strict mode is: size: ${CloudEvent.validateEvent(ceEmpty).length}, details:\n` + CloudEvent.validateEvent(ceEmpty))
console.log(`Validation output for ceEmpty, force strict mode to true is size: ${CloudEvent.validateEvent(ceEmpty, { strict: true }).length}, details:\n` + CloudEvent.validateEvent(ceEmpty, { strict: true }))

serialization examples:

// default contenttype
const ceFullSerializedStatic = CloudEvent.serializeEvent(ceFull)
const ceFullSerialized = ceFull.serialize()
console.log(`Serialization output for ceFull, details:\n` + ceFullSerialized)
const ceFullStrictSerialized = ceFullStrict.serialize()
console.log(`Serialization output for ceFullStrict, details:\n` + ceFullStrictSerialized)
// non default contenttype
const ceFullStrictOtherContentTypeSerializedStatic = CloudEvent.serializeEvent(ceFullStrictOtherContentType, {
  // encoder: (data) => '<data "encoder"="sample" />',
  encodedData: '<data "hello"="world" "year"="2019" />',
  onlyValid: true
const ceFullStrictOtherContentTypeSerialized = ceFullStrictOtherContentType.serialize({
  // encoder: (data) => '<data "encoder"="sample" />',
  encodedData: '<data "hello"="world" "year"="2019" />',
  onlyValid: true
console.log(`Serialization output for ceFullStrictOtherContentType, details:\n` + ceFullStrictOtherContentTypeSerialized)

// then use (send/store/etc) serialized instances ...

deserialization (parse) examples:

// deserialization examples
// default contenttype
console.log(`\nSome deserialization/parse examples:`)
const ceFullDeserialized = CloudEvent.deserializeEvent(ceFullSerialized)
assert(ceFullDeserialized !== null)
console.log(`cloudEvent dump: ${T.dumpObject(ceFullDeserialized, 'ceFullDeserialized')}`)
const ceFullStrictDeserializedOnlyValid = CloudEvent.deserializeEvent(ceFullStrictSerialized, { onlyValid: true })
assert(ceFullStrictDeserializedOnlyValid !== null)
console.log(`cloudEvent dump: ${T.dumpObject(ceFullStrictDeserializedOnlyValid, 'ceFullStrictDeserializedOnlyValid')}`)
// non default contenttype
const ceFullStrictOtherContentTypeDeserialized = CloudEvent.deserializeEvent(ceFullStrictOtherContentTypeSerialized, {
  // decoder: (data) => { decoder: 'Sample' },
  decodedData: { hello: 'world', year: 2019 },
  onlyValid: true
assert(ceFullStrictOtherContentTypeDeserialized !== null)
console.log(`cloudEvent dump: ${T.dumpObject(ceFullStrictOtherContentTypeDeserialized, 'ceFullStrictOtherContentTypeDeserialized')}`)

// then use (validate/send/store/etc) deserialized instances ...

Look into the example folder for more sample scripts that uses the library (inline but it's the same using it from npm registry).


Node.js 8.16.x or later.


Note that in this implementation there is even the ability to validate CloudEvent instances in a stricter way, by setting to true the attribute 'strict' in options in constructor options; or specify it during validation. That attribute when set will be put in the 'extensions' standard attribute of a CloudEvent.

You can find Code Documentation for the API of the library here.

See the CloudEvents Specification here.

In the past the name for this package was 'cloudevent.js', but it has been deprecated now and changed to the simpler 'cloudevent', so it will be easier to get it at npm.

Since v0.2 of the spec, there is no more a standard attribute to specify the version of any specific event type, so the best if to follow their recommendations, and for example add a version in the 'type' attribute (for example '-v1.0.0' at the end of its base value, or at the end of its full value) , or into the 'schemaurl' attribute but only its major version (like '-v1' or '/v1/' at the end).


  1. Fork it ( https://github.com/smartiniOnGitHub/cloudevent.js/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request


Licensed under Apache-2.0.