Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,5 @@ tsconfig.tsbuildinfo
.claude
.amazonq
.kiro
.github/instructions
.github/instructions
aidlc-docs
37 changes: 34 additions & 3 deletions docs/features/event-handler/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,42 @@ If you need to accept multiple HTTP methods in a single function, or support an

### Data validation

!!! note "Coming soon"
You can validate incoming requests and outgoing responses using any schema library that implements the [Standard Schema](https://standardschema.dev){target="_blank"} specification, such as Zod, Valibot, or ArkType.

The validation feature automatically validates request components (body, headers, path parameters, query parameters) before your handler executes, and optionally validates responses after your handler completes.

#### Basic validation

Use the `validation` option when defining routes to specify which components to validate:

=== "validation_basic.ts"

```typescript hl_lines="17 20-22 26-31"
--8<-- "examples/snippets/event-handler/rest/validation_basic.ts"
```

#### Validating multiple components

We plan to add built-in support for request and response validation using [Standard Schema](https://standardschema.dev){target="_blank"} in a future release. For the time being, you can use any validation library of your choice in your route handlers or middleware.
You can validate multiple request components simultaneously:

Please [check this issue](https://github.com/aws-powertools/powertools-lambda-typescript/issues/4516) for more details and examples, and add 👍 if you would like us to prioritize it.
=== "validation_query_headers.ts"

```typescript hl_lines="40-51"
--8<-- "examples/snippets/event-handler/rest/validation_query_headers.ts"
```

#### Error handling

Validation errors are automatically handled by the router:

- **Request validation failures** return HTTP 422 (Unprocessable Entity) with `RequestValidationError`
- **Response validation failures** return HTTP 500 (Internal Server Error) with `ResponseValidationError`

=== "validation_error_handling.ts"

```typescript hl_lines="6-10"
--8<-- "examples/snippets/event-handler/rest/validation_error_handling.ts"
```

### Accessing request details

Expand Down
116 changes: 116 additions & 0 deletions examples/snippets/event-handler/http/validation_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Validation Middleware Examples

These examples demonstrate how to use the validation middleware with the Event Handler REST router.

## Prerequisites

Install the required dependencies:

```bash
npm install @aws-lambda-powertools/event-handler zod @standard-schema/spec
```

## Examples

### Basic Validation (`validation_basic.ts`)

Shows how to:
- Validate request body with Zod schema
- Validate both request and response
- Get type inference from schemas

### Query and Headers Validation (`validation_query_headers.ts`)

Shows how to:
- Validate query parameters
- Validate request headers
- Validate multiple request components together
- Use schema transformations

### Error Handling (`validation_error_handling.ts`)

Shows how to:
- Handle validation errors with custom error handlers
- Access validation error details
- Provide different error responses in development vs production

## Supported Schema Libraries

The validation middleware supports any library that implements the Standard Schema specification:

- **Zod** (v3.x) - Shown in these examples
- **Valibot** (v1.x) - TypeScript-first schema library
- **ArkType** (v2.x) - Type-first runtime validation

## Usage with Other Schema Libraries

### Valibot Example

```typescript
import * as v from 'valibot';

const userSchema = v.object({
name: v.string(),
email: v.pipe(v.string(), v.email()),
});

app.post('/users', {
middleware: [validation({ req: { body: userSchema } })],
}, async (reqCtx) => {
// ...
});
```

### ArkType Example

```typescript
import { type } from 'arktype';

const userSchema = type({
name: 'string',
'email': 'string.email',
});

app.post('/users', {
middleware: [validation({ req: { body: userSchema } })],
}, async (reqCtx) => {
// ...
});
```

## Error Responses

### Request Validation Failure (422)

```json
{
"statusCode": 422,
"error": "RequestValidationError",
"message": "Validation failed for request body"
}
```

### Response Validation Failure (500)

```json
{
"statusCode": 500,
"error": "ResponseValidationError",
"message": "Validation failed for response body"
}
```

## Development Mode

Set `POWERTOOLS_DEV=true` to include detailed validation errors in responses:

```json
{
"statusCode": 422,
"error": "RequestValidationError",
"message": "Validation failed for request body",
"details": {
"validationError": "Expected string, received number"
}
}
```
57 changes: 57 additions & 0 deletions examples/snippets/event-handler/http/validation_basic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest';
import { z } from 'zod';

const app = new Router();

// Define schemas
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive().optional(),
});

const userResponseSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string(),
createdAt: z.string(),
});

// Validate request body
app.post(
'/users',
async () => {
return {
id: '123',
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date().toISOString(),
};
},
{
validation: { req: { body: createUserSchema } },
}
);

// Validate both request and response
app.get(
'/users/:id',
async (reqCtx) => {
const { id } = reqCtx.params;

return {
id,
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date().toISOString(),
};
},
{
validation: {
req: { path: z.object({ id: z.string().uuid() }) },
res: { body: userResponseSchema },
},
}
);

export const handler = app.resolve.bind(app);
27 changes: 27 additions & 0 deletions examples/snippets/event-handler/http/validation_error_handling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest';
import { z } from 'zod';

const app = new Router();

const userSchema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email format'),
age: z.number().int().positive('Age must be positive'),
});

app.post(
'/users',
async () => {
return {
id: '123',
name: 'John Doe',
email: 'john@example.com',
age: 30,
};
},
{
validation: { req: { body: userSchema } },
}
);

export const handler = app.resolve.bind(app);
73 changes: 73 additions & 0 deletions examples/snippets/event-handler/http/validation_query_headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest';
import { z } from 'zod';

const app = new Router();

// Validate query parameters
const listUsersQuerySchema = z.object({
page: z.string().regex(/^\d+$/).transform(Number).default('1'),
limit: z.string().regex(/^\d+$/).transform(Number).default('10'),
sort: z.enum(['name', 'email', 'createdAt']).optional(),
});

app.get(
'/users',
async () => {
return {
users: [],
pagination: {
page: 1,
limit: 10,
},
};
},
{
validation: { req: { query: listUsersQuerySchema } },
}
);

// Validate headers
const apiKeyHeaderSchema = z.object({
'x-api-key': z.string().min(32),
'content-type': z.string().optional(),
});

app.post(
'/protected',
async () => {
return { message: 'Access granted' };
},
{
validation: { req: { headers: apiKeyHeaderSchema } },
}
);

// Validate multiple components
app.post(
'/users/:id/posts',
async (reqCtx) => {
const { id } = reqCtx.params;

return {
postId: '456',
userId: id,
title: 'New Post',
};
},
{
validation: {
req: {
path: z.object({ id: z.string().uuid() }),
body: z.object({
title: z.string().min(1).max(200),
content: z.string().min(1),
}),
headers: z.object({
'content-type': z.literal('application/json'),
}),
},
},
}
);

export const handler = app.resolve.bind(app);
8 changes: 8 additions & 0 deletions packages/event-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@
"dependencies": {
"@aws-lambda-powertools/commons": "2.29.0"
},
"peerDependencies": {
"@standard-schema/spec": "^1.0.0"
},
"peerDependenciesMeta": {
"@standard-schema/spec": {
"optional": true
}
},
"keywords": [
"aws",
"lambda",
Expand Down
11 changes: 8 additions & 3 deletions packages/event-handler/src/http/Route.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import type {
HandlerResponse,
HttpMethod,
Middleware,
Path,
RouteHandler,
TypedRouteHandler,
} from '../types/http.js';

class Route {
class Route<
TReqBody = never,
TResBody extends HandlerResponse = HandlerResponse,
> {
readonly id: string;
readonly method: string;
readonly path: Path;
readonly handler: RouteHandler;
readonly handler: RouteHandler | TypedRouteHandler<TReqBody, TResBody>;
readonly middleware: Middleware[];

constructor(
method: HttpMethod,
path: Path,
handler: RouteHandler,
handler: RouteHandler | TypedRouteHandler<TReqBody, TResBody>,
middleware: Middleware[] = []
) {
this.id = `${method}:${path}`;
Expand Down
Loading
Loading