Node.js service handlers — SAP Guided Tutorial
Free sample lesson · open to everyone
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 sectionsHide sections
Visual overview
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
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?
Question 2 of 4
An after CREATE handler sends a confirmation e-mail. Later in the same request a constraint fails. What happens?
Question 3 of 4
What is the safest way to reserve stock in a CAP action under concurrent requests?
Question 4 of 4
What is the difference between req.error() and req.reject()?
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.