ERPClimb logoERPClimb
Node.js service handlers
SAP Cloud Application Programming Modelbeginner 6 min read

Node.js service handlers — SAP Guided Tutorial

Free sample lesson · open to everyone

Key takeaway

Writing before, on and after handlers in CAP Node. js: where validation belongs, how errors reject requests, how each request runs in one transaction, and why side effects such as e-mails must wait until the transaction commits.

In this lessonShow sections

Visual overview

Node.js service handlers — learning sheetFlow: before: validate → on: custom logic → after: shape results → succeeded: post-commit effects. Key ideas: IMPLEMENTING A SERVICE; THE THREE PHASES; ERRORS AND TRANSACTIONS; SIDE EFFECTS AFTER COMMIT. Watch out: Sending e-mails or calling external systems in an after handler can fire even though the transaction later rolls back — use req.on('succeeded') or the outbox.ERPClimb.com / CAP / LESSON 4/12 / LEARNING SHEETNode.js service handlers1 · HOW IT FLOWS1beforevalidate2oncustom logic3aftershape results4succeededpost-commit effects2 · KEY IDEAS EXPLAINEDImplementing A ServiceFile srv/cat-service.js next tosrv/cat-service.cds is picked up automatically.Class style: `module.exports = classCatalogService extends cds.ApplicationService {init() { ...; return super.init(); } }`.The Three Phasesbefore: input checks (`if (req.data.quantity <1) req.error(400, 'Quantity must be positive','quantity')`).on: custom implementation, e.g. an action oroverriding generic CREATE. Call `next()` tocontinue to the generic handler.Errors And Transactions`req.error(code, message, target)` collectsmultiple messages and fails the request at the endof the phase; `req.reject()` stops at once.The `target` argument lets Fiori elementshighlight the right field.Side Effects After Commit`req.on('succeeded', () => notify(order))` runsonly after a successful commit.For reliable delivery, emit events through thepersistent outbox so the message is stored in thesame transaction.3 · REMEMBER · WATCH OUTRememberHandlers register per event and entity: `this.before('CREATE','Orders', ...)`, `this.on('submitOrder', ...)`, `this.after('READ'…before = validate and enrich input; on = replace or implement theoperation; after = adjust results.`req.error()` collects errors; `req.reject()` throws immediately. Bothroll back the request's transaction.!Watch outSending e-mails or calling externalsystems in an after handler can fireeven though the transaction laterrolls back — use req.on('succeeded')or the outbox.4 · IN A REAL PROJECTA ticketing app sent confirmation e-mails from an after CREATE handler. When a later database constraintfailed, the transaction rolled back but customers still received confirmations for orders that did not exist.Moving the e-mail to req.on('succeeded') — and later to an outboxed event — removed the phantom confirmations.Original ERPClimb learning sheet • Verify against your SAP release and edition

The situation: a real project scenario

A ticketing app sent confirmation e-mails from an after CREATE handler. When a later database constraint failed, the transaction rolled back but customers still received confirmations for orders that did not exist. Moving the e-mail to req.on('succeeded') — and later to an outboxed event — removed the phantom confirmations.

Explanation

Once a service is defined, handlers add the behavior that annotations alone cannot express. In CAP Node.js, a file like srv/cat-service.js placed next to srv/cat-service.cds with the same base name is picked up automatically, typically written as module.exports = class CatalogService extends cds.ApplicationService { init() { ...; return super.init(); } }. Inside init(), const { Books, Orders } = this.entities gives you entity references without relying on hardcoded strings, and handlers are registered per event and entity: this.before('CREATE', 'Orders', ...), this.on('submitOrder', ...), this.after('READ', 'Books', ...).

These three phases map onto the request lifecycle. before is where you validate and enrich incoming data, for example if (req.data.quantity < 1) req.error(400, 'Quantity must be positive', 'quantity').

on either implements a custom action or overrides the generic handling for an operation — calling next() lets a handler fall through to the generic implementation when it doesn't need to replace it entirely.

after adjusts the result that is about to be returned, such as computing a discount field, but should avoid querying the database per row, since that reintroduces the same N+1 problem that shows up elsewhere in CAP.

Errors and transactions are tightly linked. req.error(code, message, target) collects one or more messages and fails the request at the end of the current phase, while req.reject() stops immediately; the optional target lets Fiori elements point the user at the exact field that failed. Every request runs inside one transaction, and any queries you run inside a handler automatically participate in that same transaction via cds.tx or this.tx(req).

This transactional guarantee is also why side effects need care.

req.on('succeeded', () => notify(order)) only fires after the surrounding transaction has actually committed, which avoids the common mistake of sending a notification from an after handler only to have a later constraint violation roll the whole request back — leaving the customer with a confirmation for an order that was never created.

For reliable delivery beyond a single request's lifetime, the persistent outbox stores the outgoing event in the same transaction as the data change, so publication and commit succeed or fail together.

To make this concrete: add a before CREATE handler on Orders that rejects a quantity below 1 with a field-level target; implement submitOrder by reducing stock with UPDATE ... where stock >= quantity and rejecting with 409 if no row was updated, which keeps the check and the update atomic and race-free; add an after READ handler that computes a field without querying per row; and move a notification from an after handler into req.on('succeeded'), then test what happens when the request fails.

You should be able to show a failing request that sends no notification, and a successful one that sends exactly one.

Code example

ABAP Code
const cds = require('@sap/cds');module.exports = class CatalogService extends cds.ApplicationService {  init() {    const { Books } = this.entities;    this.before('CREATE', 'Orders', req => {      if (!(req.data.quantity > 0)) req.error(400, 'Quantity must be positive', 'quantity');    });    this.on('submitOrder', async req => {      const { book, quantity } = req.data;      const n = await UPDATE(Books, book).with`stock = stock - ${quantity}`.where`stock >= ${quantity}`;      if (!n) return req.reject(409, 'Not enough stock');      req.on('succeeded', () => console.log('order confirmed', book));    });    return super.init();  }};

Watch out

Common mistakes

  • Doing validation in after handlers, after data was already written.
  • Reading and then updating stock in two statements, creating race conditions.
  • Triggering e-mails or external calls before the transaction commits.
  • Querying the database for each row in an after READ handler.

Do this

Best practices

  • Prefer declarative checks (@mandatory, @assert.range) and use handlers for what annotations cannot express.
  • Use a single conditional UPDATE for stock reservations to stay race-free.
  • Attach error targets so Fiori elements shows messages on the correct field.

In the interview

Interview angle

A strong answer explains the before/on/after phases with a real example, then shows transaction awareness: error handling with req.error vs req.reject, a race-free stock update, and post-commit side effects via req.on('succeeded') or the outbox.

Practice this lesson

Original educational case studies for SAP consultants, not official SAP certification exam questions. Verify product edition and implementation details against the current SAP documentation.

Quick check

0 of 4 questions attempted

Question 1 of 4

Where should input validation for a CREATE request normally go in CAP Node.js?

Practise this in an interview

Answer in your own words and get instant feedback, the way an interviewer would judge it.

1Walk me through the handler phases in CAP Node.js and give an example of each.

2Two users order the last copy of a book at the same time. How do you implement this in CAP so you never oversell?

Was this lesson helpful?

Keep exploring

Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.