@abstraks-dev/lambda-responses
v1.0.1
Published
Standardized Lambda response helpers with CORS support for AWS API Gateway
Downloads
31
Maintainers
Readme
@abstraks-dev/lambda-responses
Standardized Lambda response helpers with CORS support for AWS API Gateway.
Installation
npm install @abstraks-dev/lambda-responsesFeatures
- ✅ Consistent response format across all Lambda functions
- ✅ Built-in CORS headers for all responses
- ✅ Type-safe error handling
- ✅ Common HTTP status code helpers
- ✅ Automatic error response conversion
- ✅ Zero dependencies
Usage
Basic Success Response
import { createSuccessResponse } from '@abstraks-dev/lambda-responses';
export const handler = async (event) => {
const data = { message: 'Hello World', timestamp: new Date().toISOString() };
return createSuccessResponse(data);
};
// Returns:
// {
// statusCode: 200,
// headers: { /* CORS headers */ },
// body: '{"message":"Hello World","timestamp":"2024-01-01T00:00:00.000Z"}'
// }Error Responses
import {
createBadRequestResponse,
createUnauthorizedResponse,
createNotFoundResponse,
createServerErrorResponse,
} from '@abstraks-dev/lambda-responses';
// Bad Request (400)
export const handler = async (event) => {
if (!event.body) {
return createBadRequestResponse('Request body is required');
}
// ... your logic
};
// Unauthorized (401)
if (!isAuthenticated) {
return createUnauthorizedResponse('Invalid token');
}
// Not Found (404)
if (!user) {
return createNotFoundResponse('User not found');
}
// Server Error (500)
try {
// ... your logic
} catch (error) {
return createServerErrorResponse('Database connection failed');
}Error Response from Error Object
import { createErrorResponse } from '@abstraks-dev/lambda-responses';
export const handler = async (event) => {
try {
// ... your logic
} catch (error) {
// Automatically uses error.statusCode if present, defaults to 500
return createErrorResponse(error);
}
};
// Custom status code:
const error = new Error('Resource not found');
error.statusCode = 404;
return createErrorResponse(error);Validation Errors
import { createValidationErrorResponse } from '@abstraks-dev/lambda-responses';
const validationErrors = [
{ field: 'email', message: 'Invalid email format' },
{ field: 'password', message: 'Password must be at least 8 characters' },
];
return createValidationErrorResponse(validationErrors);
// Returns:
// {
// statusCode: 422,
// headers: { /* CORS headers */ },
// body: '{"error":"Validation failed","details":[...]}'
// }CORS Preflight (OPTIONS)
import { createOptionsResponse } from '@abstraks-dev/lambda-responses';
export const handler = async (event) => {
if (event.httpMethod === 'OPTIONS') {
return createOptionsResponse();
}
// ... your logic
};Error Handling Middleware
import { withErrorHandling } from '@abstraks-dev/lambda-responses';
const myHandler = async (event, context) => {
// If this throws an error, it will automatically be converted to an error response
const data = await fetchData();
return createSuccessResponse(data);
};
// Wrap with automatic error handling
export const handler = withErrorHandling(myHandler);Custom Status Codes
import { createSuccessResponse } from '@abstraks-dev/lambda-responses';
// Created (201)
return createSuccessResponse({ id: '123', created: true }, 201);
// Accepted (202)
return createSuccessResponse({ queued: true }, 202);
// No Content (204)
return createSuccessResponse({}, 204);Custom Headers
import {
createSuccessResponse,
CORS_HEADERS,
} from '@abstraks-dev/lambda-responses';
const customHeaders = {
...CORS_HEADERS,
'X-Custom-Header': 'value',
'Cache-Control': 'max-age=3600',
};
return createSuccessResponse(data, 200, customHeaders);API Reference
Response Creators
createSuccessResponse(data, statusCode?, headers?)- Create success response (default 200)createErrorResponse(error, headers?)- Create error response from Error objectcreateBadRequestResponse(message?, headers?)- Create 400 responsecreateUnauthorizedResponse(message?, headers?)- Create 401 responsecreateForbiddenResponse(message?, headers?)- Create 403 responsecreateNotFoundResponse(message?, headers?)- Create 404 responsecreateValidationErrorResponse(errors, headers?)- Create 422 responsecreateServerErrorResponse(message?, headers?)- Create 500 responsecreateOptionsResponse(headers?)- Create OPTIONS response for CORS preflight
Utilities
createResponse(statusCode, body, headers?)- Low-level response creatorcreateErrorResponseWithCode(statusCode, message, headers?)- Create error with specific codewithErrorHandling(handler)- Wrap handler with automatic error handlingCORS_HEADERS- Default CORS headers object
Response Format
All responses follow this structure:
{
statusCode: number,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Credentials': 'true',
},
body: string // JSON stringified
}Success Response Body
{
// Your data directly
}Error Response Body
{
"error": "Error message"
}Validation Error Response Body
{
"error": "Validation failed",
"details": [{ "field": "email", "message": "Invalid format" }]
}Migration from Existing Code
Before
// Old code in each service
export const createErrorResponse = (error) => {
return {
statusCode: error.statusCode || 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Credentials': 'true',
},
body: JSON.stringify({ error: error.message }),
};
};After
// New code using shared module
import { createErrorResponse } from '@abstraks-dev/lambda-responses';
// That's it! Same functionality, maintained in one placeTesting
The package includes comprehensive tests with 100% coverage:
npm testLicense
MIT
Contributing
See the main shared-modules repository for contribution guidelines.
