Services and Custom Handlers in Node.js

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A CAP service answers most requests without any code from you: reading, creating, updating and deleting rows is done by built-in generic providers. Sooner or later a business rule appears that the model cannot say, such as "a claim must not have a negative amount" or "two claims must not have the same title", and that rule goes into an event handler, a small function that CAP calls at a defined moment while it processes a request. This page shows how to write handlers in Node.js: where the file goes, how the three phases before, on and after differ, how a handler reports an error with req.error or req.reject, how to look at the data with a CQL query, and what the client really receives. It starts from the handler file of this site’s expenses lab, says what that file already does, and then grows it into a teaching version. The page is written for CAP Node.js 10.2 (@sap/cds 10.2.2, which needs Node.js 22.12 or newer). CAP Java 5.2 (Java 21 or newer, Java 25 recommended) has the same event model with annotated Java classes, which a later page covers. Nothing here depends on the SAP BTP runtime (Cloud Foundry or Kyma): handlers are ordinary code inside the application, and every listing on this page ran locally with the SQLite in-memory database and needed no SAP BTP account. SAP BTP is still the documented product name, and SAP now presents its capabilities as part of SAP Business AI Platform.

Before you read

Key terms

  • Event handler: a function registered with a service to run in the before, on or after phase of an event.

  • Application service: the CAP class cds.ApplicationService, which brings the generic providers that serve reads, writes and drafts, and which your service class extends.

  • Generic provider: built-in service behavior that serves requests from the model alone, without code written by you.

  • CQL (Conceptual Query Language): the SQL-like language in which CAP queries are written, independent of any database.

  • Draft: an unsaved working copy of a record that a Fiori app edits and later activates, which CAP stores separately from the active data.

  • OData: the web protocol in which the lab service answers, and whose error format carries the messages of your handlers.

Where handlers live

The official guide says that most use cases are covered by generic runtimes, so the need for custom code is greatly reduced, and it advises trying declarative techniques first, such as status flows and declarative constraints, before reaching for imperative code. When a rule does need code, the easiest way in Node.js is a .js file with the same name as the service’s .cds file, placed next to it. In the lab that is srv/expense-service.cds for the definition and srv/expense-service.js for the implementation. The server log of the lab confirms the pairing when it starts: it lists the service with decl: 'srv/expense-service.cds:2' and impl: 'srv/expense-service.js'.

The implementation is a class that extends cds.ApplicationService, and the handlers are registered in its method init(). The Node.js reference describes it this way: the class is a subclass of cds.Service, or more commonly of cds.ApplicationService, to benefit from the generic out-of-the-box implementations, and the handlers are commonly registered in init(). The call return super.init() at the end hands control to the parent class, which registers the generic providers; that is why the lab’s service still reads and writes claims although its own file mentions only one rule.

What the lab already does

The handler file of the lab is short. It is shown here exactly as it is in modules/ROOT/examples/sap-lab/expenses/srv/expense-service.js of this site’s repository.

import cds from '@sap/cds'
export default class ExpenseService extends cds.ApplicationService {
  init() {
    this.before('SAVE', 'Claims', req => {
      if (req.data.amount < 0) req.error(400, 'Amount must not be negative', 'in/amount')
    })
    return super.init()
  }
}

It registers one handler for the before phase of the event SAVE on the entity Claims. The Node.js documentation says that SAVE fires when a user saves or activates a draft, and that on an entity without drafts it is a shortcut for CREATE plus UPDATE. The service of the lab has @odata.draft.enabled, so the rule runs when a draft is activated. It looks at req.data, the payload of the request, and calls req.error with an HTTP status, a message and a target, the name of the input field the error belongs to. The lab ships one test for the service, which only reads the list of claims. Run in a copy of the lab after npm ci, it printed this (the output is complete):

$ npm test

> expenses@1.0.0 test
> node --test

✔ lists claims (151.602292ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 204.171542

Source: real output of npm test (the node --test runner, with @cap-js/cds-test 1.0.2 as a development dependency of the lab) in a copy of the lab, CAP Node.js 10.2; the test helper cds.test is documented at CAP: Testing with cds.test

The test does not exercise the negative-amount rule, so the next listing does it by hand. With the lab server running (PORT=4119 npx cds-serve, mocked authentication, so requests are anonymous), a POST to Claims with a negative amount does not fail, because on a draft-enabled entity it creates a draft, and drafts are not validated yet. Activating the draft with the OData action draftActivate triggers SAVE. The commands and the real response:

$ curl -s -X POST http://localhost:4119/odata/v4/expense/Claims \
    -H 'Content-Type: application/json' -d '{"title":"Taxi","amount":-5}'
(HTTP 201, the new draft, IsActiveEntity false; ID c6126cbe-3057-464e-92c3-533d6186e007)

$ curl -si -X POST "http://localhost:4119/odata/v4/expense/Claims(ID=c6126cbe-3057-464e-92c3-533d6186e007,IsActiveEntity=false)/ExpenseService.draftActivate" \
    -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"error":{"message":"Amount must not be negative","code":"400","target":"in/amount","@Common.numericSeverity":4}}

Source: real output of the lab server (CAP Node.js 10.2); the draft event is described at CAP: Serving Fiori UIs in Node.js; response headers other than the status line and Content-Type are left out (shortened)

The message, the 400 and the target in/amount are exactly what the handler passed to req.error. The status became the HTTP status, the number became the code, and the field @Common.numericSeverity is added by the OData layer, not by the handler. The claim was not stored as an active claim; the final listing of this page, read after several more activations, does not contain it.

The three phases

An event handler is registered for a hook, an event and optionally an entity. The official scheme is a hook (on, before or after), an event and an entity, which map to a handler function. The events are the CRUD names CREATE, READ, UPDATE and DELETE, the aliases and draft events such as SAVE, each, and the names of custom actions. The entity can be written as a string, as an entity from this.entities, as an array, or as '*' for all entities.

The three hooks run in this order and have different jobs.

Hook When it runs Typical use

before

Before the on handlers. All matching before handlers run concurrently.

Validating input and changing req.data.

on

Fulfills the request. For requests, the handlers form a chain in which each handler decides whether to call next().

Reading and writing the database, or replacing that work.

after

After the on handlers, with the result as the first argument. All matching after handlers run concurrently.

Enriching outbound data.

The generic provider is itself an on handler registered by super.init(). A handler of your own that is registered with on before that call comes first in the chain and can answer the request alone or call next() to let the built-in behavior continue. The documentation also states a rule of thumb: custom domain logic mostly belongs in before or after handlers, and on handlers are mostly needed for custom actions and functions. Between the phases the runtime checks req.errors: the next phase starts only if no error was recorded, and an error stops the request with an error response.

A teaching version of the service

To see all three phases work, the lab copy was changed into a teaching version. It is not the lab file; it is a model made for this page, so both files are shown in full. The service definition gains one calculated field, needsReview, declared as a virtual element: the documentation says a virtual element is not stored in the database, is part of the OData metadata and is not writable for the client, and that during reads you provide its values in an after handler.

using { sap.guide.expenses as db } from '../db/schema';
service ExpenseService {
  @odata.draft.enabled
  entity Claims as projection on db.Claims {
    *,
    virtual needsReview : Boolean
  };
}

The handler file registers four handlers: the validation as a named function, two logging handlers that show the order of the phases, and an after handler that fills needsReview.

import cds from '@sap/cds'
export default class ExpenseService extends cds.ApplicationService {
  init() {
    const { Claims } = this.entities
    this.before('SAVE', Claims, validateClaim)
    this.before('READ', Claims, req => console.log('before READ'))
    this.on('READ', Claims, (req, next) => {
      console.log('on READ')
      return next()
    })
    this.after('each', Claims, claim => {
      claim.needsReview = Number(claim.amount) > 100
    })
    return super.init()
  }
}

async function validateClaim(req) {
  const { ID, title, amount } = req.data
  if (!title?.trim()) req.error(400, 'Title is required', 'in/title')
  if (amount < 0) req.error(400, 'Amount must not be negative', 'in/amount')
  if (title) {
    const { Claims } = this.entities
    const twin = await SELECT.one.from(Claims).where`title = ${title} and ID != ${ID}`
    if (twin) req.error(409, `A claim titled "${title}" already exists`, 'in/title')
  }
}

Reading the listing from the top:

  • this.entities gives the entities of this service, and passing the entity itself (Claims) instead of a string is one of the documented ways to name the target.

  • The on handler for READ takes two arguments, the request req and next. Returning next() passes control to the next handler in the chain, which here is the generic provider that reads the database. Without that call, the chain would stop at this handler and the data would never be read.

  • after('each', ...) is documented as a shorthand that calls the handler once per row of a READ result. The documentation adds that such a handler must be synchronous, which this one is. The amount arrives as a string from the OData layer, hence Number(...).

  • validateClaim is a named function rather than an arrow function. The documentation recommends named functions as handlers, because inside a named function this is the transactional copy of the service, with access to the transaction and tenant, while inside an arrow function it is the base instance. The validation uses this.entities for that reason.

Start the server in the lab copy with PORT=4119 npx cds-serve and read the claims. The first request shows the phases in the server log and needsReview in the answer:

$ curl -s "http://localhost:4119/odata/v4/expense/Claims?\$select=title,amount,needsReview"
{"@odata.context":"$metadata#Claims","value":[{"title":"Train ticket","amount":"45.50","ID":"11111111-1111-1111-1111-111111111111","needsReview":false,"IsActiveEntity":true}]}

(server log)
[odata] - GET /odata/v4/expense/Claims {
}
before READ
on READ

Source: real output of the teaching version in the copy of the lab (CAP Node.js 10.2, SQLite in memory); the log is shortened to the lines of this request, and the $ of the query options is escaped in the commands so that the shell leaves it alone

The log lines before READ and on READ appear in the order of the phases, and needsReview comes from the after handler, because the field is not in the database.

Reporting errors: req.error and req.reject

A handler has two ways to refuse a request, and the choice is about timing. req.reject constructs an error and throws it at once, which ends the handler. req.error constructs and records an error without throwing, so the handler continues and can record more. The recorded errors are collected in req.errors, which is undefined until the first call. After each phase the framework checks req.errors, and if it is set, rejects the request with one aggregate error that contains them all. That is the right shape for validation, because a user who made three mistakes sees three messages in one round trip instead of fixing them one at a time. Both methods accept the same arguments: an object with status, code, message, target and args, or the short form of status, message, target and args used above.

The validation of the teaching version records up to three errors. Each request in the next listing creates a draft and activates it, with the commands wrapped in a small shell function of the scratch folder (the same two curl calls as in the previous section). The output is the real response, shortened to the status line, the content type and the body:

--- draft {"title":"Taxi","amount":-5}
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"error":{"message":"Amount must not be negative","code":"400","target":"in/amount","@Common.numericSeverity":4}}

--- draft {"title":" ","amount":-5}
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"error":{"message":"Multiple errors occurred, see details below.","code":"MULTIPLE_ERRORS","target":"in","details":[{"message":"Title is required","code":"400","target":"in/title","@Common.numericSeverity":4},{"message":"Amount must not be negative","code":"400","target":"in/amount","@Common.numericSeverity":4}],"@Common.numericSeverity":4}}

Source: real output of the teaching version (CAP Node.js 10.2); error responses are described at CAP: Events and Requests in Node.js

The first draft broke one rule, so the response holds one error. The second broke two, so the response has the code MULTIPLE_ERRORS and a details array with one entry per req.error call, each with its own target. The documentation gives the same equivalence: collected errors end up as a rejection with the code MULTIPLE_ERRORS and a list of details. A Fiori element screen uses the targets to mark the fields that caused the errors. The related methods req.info, req.warn and req.notify record messages that go back next to a successful answer, in a response header, and do not abort anything.

The documentation also states a rule for the status code that is worth remembering. If you give a status, it becomes the HTTP status; a numeric code in the range of 300 to 600 does the same when no status is given. Errors with a 5xx status are returned to the client with only a generic message in production, so a rule that the user should read, such as a duplicate, uses a 4xx status as in the listing, 409 for a conflict.

A CQL query inside a handler

The last rule of validateClaim needs data the request does not contain: whether another claim already has this title. A handler gets that with a query. CAP queries are written in CQL, and in Node.js the fluent API of cds.ql is available as the global objects SELECT, INSERT, UPSERT, UPDATE and DELETE. Queries are first-class objects: building one only captures it, and awaiting it runs it on the database service, or on the service you bind it to. The query of the listing, SELECT.one.from(Claims).where followed by a tagged template, returns a single row, if there is one, instead of an array.

The part ${title} and ${ID} inside the template deserves attention. The Node.js documentation says all the APIs are designed to avoid SQL injection by default: the values become parameters of the query object and are sent to the database as bound values, and never glued into SQL text. The one mistake it warns about is concatenating user input into the CQL or SQL string, and it adds that a tagged template must never be wrapped in parentheses, because then the string is concatenated before the tag sees it. The third scenario of the next listing shows the rule at work. Activating a draft whose title already exists as an active claim (the seed row is called Train ticket) is refused with the 409 of the handler, and a draft that follows all the rules is stored, shown together with the active claims read afterwards:

--- draft {"title":"Train ticket","amount":10}
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8

{"error":{"message":"A claim titled \"Train ticket\" already exists","code":"409","target":"in/title","@Common.numericSeverity":4}}

--- draft {"title":"Hotel","amount":250}
HTTP/1.1 201 Created
location: ../Claims(ID=797e1f2a-631f-4676-b286-0f382687a90a,IsActiveEntity=true)
Content-Type: application/json; charset=utf-8; ieee754compatible=true

{"@odata.context":"../$metadata#Claims/$entity","ID":"797e1f2a-631f-4676-b286-0f382687a90a","createdAt":"2026-11-13T14:23:59.948Z","createdBy":"anonymous","modifiedAt":"2026-11-13T14:23:59.948Z","modifiedBy":"anonymous","title":"Hotel","status":"N","amount":"250.00","needsReview":true,"HasActiveEntity":false,"HasDraftEntity":false,"IsActiveEntity":true}

$ curl -s "http://localhost:4119/odata/v4/expense/Claims?\$select=title,amount,needsReview&\$filter=IsActiveEntity%20eq%20true&\$orderby=title"
{"@odata.context":"$metadata#Claims","value":[{"title":"Hotel","amount":"250.00","ID":"797e1f2a-631f-4676-b286-0f382687a90a","needsReview":true,"IsActiveEntity":true},{"title":"Train ticket","amount":"45.50","ID":"11111111-1111-1111-1111-111111111111","needsReview":false,"IsActiveEntity":true}]}

Source: real output of the teaching version (CAP Node.js 10.2); query building and injection safety are described at CAP: Querying in Node.js

The comparison ID != ${ID} keeps a claim from being its own duplicate when an existing claim is edited and saved again. The amount of 250 raised needsReview to true in the after handler, and the saved claim is read back with its two active rows. The seed row of the lab and the new claim exist only in memory: the in-memory SQLite database is rebuilt from the CSV file every time the server starts.

What to do in a handler and what to leave to the model

The official guide is clear about the order of preference, and the example above follows its advice only in part. A rule that can be written as an expression belongs in the model. The constraints guide shows annotations such as @mandatory and @assert on service elements, which the runtime enforces on every write and turns into error responses, with default translations for some of them, and it notes that the reference page of req.reject itself recommends @mandatory over a hand-written check for a required field. In this page’s teaching service, "title is required" would be better stated that way. It is written as code here because showing req.error collecting several messages needs rules to collect. Rules that need the state of another record or a decision at run time, like the duplicate check, stay in a handler.

Three habits keep handlers healthy. Register handlers in init() and finish with return super.init(). Prefer before for checks and after for enrichment, and keep on for custom actions. Do not mix after handlers that depend on each other, since the documentation warns that asynchronous after handlers run in parallel and can race. For a complete service, automated tests that call the service, as the lab’s test does with GET, are the way to keep these rules from silently breaking; the lab’s single test is a starting point, not a check of the rules on this page.

Summary

  • Custom code goes into a class that extends cds.ApplicationService, in a .js file next to the service’s .cds file, with handlers registered in init() and return super.init() at the end.

  • Handlers run in three phases: before for validation, on for fulfilling the request (chained with next()), and after for enriching the result, for example with after('each', ...) per row.

  • The lab’s handler already validates one thing: it records a 400 error with the target in/amount in the before phase of SAVE, which fires when a draft is activated, and the real response is shown above.

  • req.error records an error and lets the handler continue, so several problems come back together as MULTIPLE_ERRORS; req.reject throws at once. A 4xx status is for messages the user should read.

  • A handler reads data with CQL, such as SELECT.one.from(Claims).where and a tagged template, whose values are bound parameters; never concatenate user input into a query.

  • Prefer declarative constraints in the model, and keep handlers for rules that need run-time data.

Try it

To do this by hand, follow the guide Model a Domain and Add Custom Logic in CAP: it adds associations, a composition, a validation handler and an action.