Security
nestjs-odata includes built-in protections against common DoS and resource exhaustion attacks from unbounded OData queries. All limits are enforced server-side — clients cannot bypass them.
Query limits
maxTop — result size limit
Limits the number of entities a client can request in a single query.
Default: 1000
ODataModule.forRoot({
serviceRoot: '/odata',
maxTop: 500, // No more than 500 entities per request
})Rejection, not clamping
nestjs-odata rejects $top values that exceed maxTop with HTTP 400. It does not silently adjust the value. This ensures clients know exactly what they are receiving and prevents silent data truncation.
GET /odata/Products?$top=10000
HTTP/1.1 400 Bad Request
{
"error": {
"code": "QueryOptionExceedsLimit",
"message": "$top value 10000 exceeds maximum allowed value 500"
}
}maxExpandDepth — $expand nesting limit
Limits the depth of $expand nesting. Each additional level multiplies the number of JOIN operations and result size.
Default: 2
ODataModule.forRoot({
serviceRoot: '/odata',
maxExpandDepth: 3, // Allow: A($expand=B($expand=C)) — but not deeper
})Exceeding the limit:
GET /odata/Customers?$expand=orders($expand=items($expand=product))
// With maxExpandDepth=2:
HTTP/1.1 400 Bad Request
{
"error": {
"code": "ExpandDepthExceeded",
"message": "$expand depth 3 exceeds maximum allowed depth 2"
}
}$levels counts against the same limit: each level is one more level of $expand, a $levels value that goes past maxExpandDepth is rejected with 400 before any query is built, and $levels=max stops at maxExpandDepth.
maxFilterDepth — $filter expression nesting limit
Limits the depth of nested logical expressions in $filter. Deeply nested filters can cause exponential parse tree growth.
Default: 10
ODataModule.forRoot({
serviceRoot: '/odata',
maxFilterDepth: 15, // Allow up to 15 levels of nesting
})Exceeding the limit:
GET /odata/Products?$filter=((((((((((((name eq 'x'))))))))))))))
// With maxFilterDepth=10:
HTTP/1.1 400 Bad Request
{
"error": {
"code": "FilterDepthExceeded",
"message": "$filter expression exceeds maximum nesting depth of 10"
}
}Per-entity overrides
Override global limits for specific entity sets. Per-entity overrides take precedence over global options.
import { Injectable, OnModuleInit } from '@nestjs/common'
import { EdmRegistry } from '@nestjs-odata/core'
@Injectable()
export class SecurityConfigService implements OnModuleInit {
constructor(private readonly edmRegistry: EdmRegistry) {}
onModuleInit(): void {
// Expensive entity: restrict to 50 items
this.edmRegistry.setEntitySecurityOptions('Orders', {
maxTop: 50,
maxExpandDepth: 1,
})
// Read-heavy entity: allow larger pages
this.edmRegistry.setEntitySecurityOptions('Products', {
maxTop: 2000,
})
// Sensitive entity: very tight filter nesting
this.edmRegistry.setEntitySecurityOptions('Customers', {
maxTop: 100,
maxFilterDepth: 5,
})
}
}Register the service in your module:
@Module({
providers: [SecurityConfigService],
})
export class AppModule {}Override precedence
- Per-entity override (highest priority)
- Global
ODataModuleOptions - Built-in defaults (lowest priority)
ETag concurrency control
Entities decorated with @ODataETag() get automatic optimistic concurrency control:
- Write protection: when a
PATCH,PUTorDELETE(also inside$batch) carries anIf-Matchheader that does not match the current ETag (another client modified the entity), the server returns412 Precondition Failedand changes nothing. So does a write whoseIf-None-Matchmatches the current ETag (*matches any existing entity). - Requiring
If-Match: by default a write withoutIf-Matchis allowed, so clients that want the protection must send the header. SetrequireIfMatch: trueon an entity set'sforFeature()item to answer such writes with428 Precondition Required(HTTP and$batch, also with write handlers);$metadatathen advertisesCore.OptimisticConcurrencyon the entity set. See CRUD: Requiring If-Match. - Read optimization:
GETsingle entity supportsIf-None-Match. If the ETag matches (entity unchanged), the server returns304 Not Modifiedwith no body. Collections carry@odata.etagon each entity.
This prevents lost-update scenarios in concurrent environments without pessimistic locking.
If-Match: * matches any existing entity, and a comma-separated list matches when any entry does. The etag option of ODataTypeOrmModule.forFeature() items sets the ETag source per entity set (a version column, a function); with write handlers, the handler receives If-Match and must check it in the same transaction as its write.
import { ODataETag } from '@nestjs-odata/core'
@Entity()
export class Product {
@UpdateDateColumn()
@ODataETag()
updatedAt: Date
}Disable Express's own ETags
Express's default etag setting adds a hash ETag to every JSON response, including 400/404 errors, collections and $metadata. Those are not OData ETags: a client that echoes one in If-Match always gets 412. Call app.set('etag', false) on the Express application of an OData service. The library logs a warning at startup while the setting is on, but does not change it for you.
Write bodies
Writes only persist properties of the entity type (OData 4.01 Part 1 §11.4.2):
- a property that is not in the EDM, including columns hidden with
@ODataExcludeorselect: false, answers400 Bad Requestand nothing is written, so hidden columns can't be mass-assigned through POST, PATCH or PUT (or$batch); - computed properties (create/update timestamps, version and generated columns, annotated
Core.Computed) and, on PATCH/PUT, key properties are ignored: the URL key decides the row.
ignoreUnknownProperties: true drops unknown properties instead of answering 400; they are still never persisted.
Enriched error details
Validation and parse errors include additional context to help developers diagnose issues:
availableProperties: When a$selector$filterreferences an unknown property, the error response includes the list of valid property names for the entity set.queryContext: When a$filteror other query option has a parse error, the error response includes a snippet of the query around the error position.
{
"error": {
"code": "BadRequest",
"message": "Property 'naem' not found on entity 'Product'",
"details": [
{
"code": "AvailableProperties",
"message": "Available properties: id, name, price, inStock",
"target": "availableProperties",
"value": ["id", "name", "price", "inStock"]
}
]
}
}Every entry of details has a code and a message (OData JSON Format 4.01 §21.1); value is an extra, service-defined member. A parse error's detail is { "code": "QueryOption", "message": "Error near: …", "target": "…" }.
Mapping your own errors
Unknown exceptions become a generic 500, and the message of every 5xx error (including a ServiceUnavailableException's) is replaced by a generic one, so internal details never leak. This holds for $batch operations too. To give clients meaningful errors for your own exception types (or for database errors such as unique violations), use the errorMapper option. Whatever it returns is sent to the client as is.
Parameterized queries
All $filter values are translated to parameterized TypeORM queries — never string interpolation. This prevents SQL injection.
$filter=name eq 'O''Malley' → WHERE name = $1 params: ["O'Malley"]
$filter=price lt 100 → WHERE price < $1 params: [100]Single quotes in string literals are properly escaped before parameterization.
Authentication and authorization
nestjs-odata does not provide authentication. Use standard NestJS guards:
import { UseGuards } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
@ODataController('Products')
@UseGuards(AuthGuard('jwt')) // Apply to all routes in the controller
export class ProductsController {
// ...
}Or apply guards to specific operations:
@ODataDelete('Products')
@UseGuards(AuthGuard('jwt'), AdminGuard)
async deleteProduct(@Param('key') key: string) {
return this.handler.handleDelete(key, 'Products')
}$batch
Operations inside POST {serviceRoot}/$batch are authorized exactly like the same request sent on its own (OData 4.01 Part 1 §11.7): each one is dispatched through your application's HTTP stack and reaches its route with the route's guards, global guards, middleware, interceptors and pipes. A guard that denies DELETE /odata/Products/1 (403) also denies DELETE Products(1) in a batch; inside a changeset, the denial fails and rolls back the whole changeset.
- Operations inherit the credentials of the
$batchrequest (Authorization,Cookie, custom headers): OData forbids authentication headers on individual parts (§11.7.7.1). Conditional andPreferheaders are never inherited. - An operation can only reach routes a standalone request can reach: entity sets or methods without a route answer
404. - Operations are confined to the service root: a URL that resolves outside it (
/auth/login,../admin, an absolute URL to another path) answers400without reaching any route, so$batchcan't be used to call other application routes behind path-based controls. A nested$batchoperation answers400too. getODataBatchPart()(from@nestjs-odata/core) is defined while a batch operation runs, so a guard can apply a batch-specific policy (for example refuse deletes inside$batch).ODataTypeOrmModule.forRoot({ batch: { enabled: false } })turns the endpoint off (404);batch: { entitySets: [...] }allow-lists the entity sets operations may target (other targets answer 403 without reaching their route). See $batch.batch.entitySetschecks every entity set an operation reaches: the resource path, navigation segments (Products(1)/Supplier) and$expandtargets. Navigation paths inside$filterare not checked — rely on row-level scopes for row access.- A
$batchcannot be nested, however its URL is spelled ($BATCH), nor be reached from inside a batch operation, so the 100-operation limit cannot be multiplied. - Each operation has a time limit (
batch.operationTimeout, default 30 s; then 504): a stuck route cannot hold a changeset's transaction and row locks indefinitely. - The batch operation and the changeset's entity manager travel on the operation's request object, not only in
AsyncLocalStorage, so middleware that resumesnext()from a foreign async context cannot make a changeset write commit outside its transaction (Express adapter). - Each operation counts as a request for rate limiters such as
@nestjs/throttler; the batch is limited to 100 operations.
Upgrading from versions before this change
Earlier versions executed $batch operations directly against TypeORM: route guards, interceptors and pipes of @ODataController routes did not run for them (only row-level scopes, write handlers and guards on the $batch route itself applied). If you relied on a global guard or middleware on $batch to compensate, it still works; if you relied on the bypass, operations your route guards deny are now refused.
Row-level access
Guards decide whether a request may call a route. To restrict which rows it sees, register a row-level scope per entity set. Scopes apply to collections, $count, by-key reads, every $expand path, lambdas in $filter, $apply, $batch and the existence checks of writes. Set requireScope: true so an entity set without a scope fails closed.
Write handlers receive the raw parsed body: there is no repository column whitelist, so validate it there. Deep inserts never write nested entities of a handler-backed entity set through the repository (400).
Recommended production configuration
ODataModule.forRoot({
serviceRoot: '/odata',
namespace: 'MyApp',
maxTop: 500, // Conservative limit
maxExpandDepth: 2, // Default — do not increase without profiling
maxFilterDepth: 10, // Default — sufficient for most use cases
controllers: [...],
})Apply rate limiting at the infrastructure layer (reverse proxy, API gateway, or @nestjs/throttler) — the OData library does not duplicate this concern.