npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@abstraks-dev/lambda-responses

v1.0.1

Published

Standardized Lambda response helpers with CORS support for AWS API Gateway

Downloads

31

Readme

@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.