New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@abstraks-dev/lambda-responses

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@abstraks-dev/lambda-responses

Standardized Lambda response helpers with CORS support for AWS API Gateway

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

@abstraks-dev/lambda-responses

Standardized Lambda response helpers with CORS support for AWS API Gateway.

Installation

npm install @abstraks-dev/lambda-responses

Features

  • ✅ 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 object
  • createBadRequestResponse(message?, headers?) - Create 400 response
  • createUnauthorizedResponse(message?, headers?) - Create 401 response
  • createForbiddenResponse(message?, headers?) - Create 403 response
  • createNotFoundResponse(message?, headers?) - Create 404 response
  • createValidationErrorResponse(errors, headers?) - Create 422 response
  • createServerErrorResponse(message?, headers?) - Create 500 response
  • createOptionsResponse(headers?) - Create OPTIONS response for CORS preflight

Utilities

  • createResponse(statusCode, body, headers?) - Low-level response creator
  • createErrorResponseWithCode(statusCode, message, headers?) - Create error with specific code
  • withErrorHandling(handler) - Wrap handler with automatic error handling
  • CORS_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 place

Testing

The package includes comprehensive tests with 100% coverage:

npm test

License

MIT

Contributing

See the main shared-modules repository for contribution guidelines.

Keywords

aws

FAQs

Package last updated on 20 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts