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

@timmons-group/snack-utils

v0.2.1

Published

Essential utilities for building robust serverless Node.js applications. This package provides logging, profiling, and HTTP response utilities optimized for Lambda and serverless environments.

Downloads

525

Readme

Shared Node Architecture Component Kit (SNACK) Utils

Essential utilities for building robust serverless Node.js applications. This package provides logging, profiling, and HTTP response utilities optimized for Lambda and serverless environments.

Installation

npm install @timmons-group/snack-utils

Components

Logger

A configurable logging utility with multiple log levels and structured output, designed for serverless environments.

Features

  • Multiple Log Levels: ERROR, WARN, INFO
  • Module-based Logging: Create loggers for specific modules
  • Environment Configuration: Control logging via environment variables
  • Structured Output: Consistent log message formatting
  • Performance Optimized: Minimal overhead when logging is disabled

Configuration

Set the LOG_LEVEL environment variable to control logging output:

  • ERROR - Only error messages (default)
  • WARN - Warning and error messages
  • INFO - All messages (info, warning, error)

Usage

import { createLoggers, setLogLevel } from '@timmons-group/snack-utils';

// Create module-specific loggers
const { log, warn, error } = createLoggers('UserService');

// Log messages at different levels
log('Processing user request');           // Info level
warn('User session expires soon');       // Warning level
error('Failed to authenticate user');    // Error level

// Programmatically set log level
setLogLevel('INFO');

Advanced Usage:

import { createLoggers } from '@timmons-group/snack-utils';

// Multiple modules
const userLogger = createLoggers('UserService');
const dbLogger = createLoggers('DatabaseService');

userLogger.log('User authenticated successfully');
dbLogger.warn('Connection pool running low');

Profiler

A lightweight performance profiling utility for measuring execution time across different code blocks.

Features

  • Code Block Timing: Measure execution time between markers
  • Nested Profiling: Support for hierarchical timing measurements
  • Detailed Reports: Comprehensive timing analysis
  • Memory Efficient: Minimal memory footprint
  • Easy Integration: Simple API for existing code

Usage

import { createProfiler } from '@timmons-group/snack-utils';

const profiler = createProfiler();

// Mark timing points
profiler.tab('Database Query');
const users = await db.query('SELECT * FROM users');

profiler.tab('Data Processing');
const processedUsers = users.map(processUser);

profiler.tab('Response Formatting');
const response = formatResponse(processedUsers);

profiler.end();

// Generate timing report
profiler.report();
// Output:
// Database Query: 45ms
// Data Processing: 12ms
// Response Formatting: 3ms
// Total: 60ms

Advanced Profiling:

import { createProfiler } from '@timmons-group/snack-utils';

const profiler = createProfiler();

// Measure API endpoint performance
profiler.tab('Request Validation');
validateRequest(event);

profiler.tab('Authentication');
const user = await authenticateUser(token);

profiler.tab('Business Logic');
const result = await processBusinessLogic(user, data);

profiler.tab('Response Generation');
const response = generateResponse(result);

profiler.end();
profiler.report(); // Detailed breakdown of each operation

HTTP Responses

Standardized HTTP response utilities for AWS Lambda functions with consistent formatting and proper headers.

Features

  • Standard Status Codes: Pre-configured common HTTP responses
  • CORS Support: Automatic CORS header handling
  • JSON Serialization: Automatic JSON response formatting
  • Lambda Optimized: Designed for AWS Lambda return format
  • Type Safety: Consistent response structure

Available Response Types

  • jsonSuccess(data) - 200 OK with JSON data
  • noContent() - 204 No Content
  • notFound(message?) - 404 Not Found
  • badRequest(message?) - 400 Bad Request
  • unauthorized(message?) - 401 Unauthorized
  • forbidden(message?) - 403 Forbidden
  • serverError(message?) - 500 Internal Server Error

Usage

import { responses } from '@timmons-group/snack-utils';

// Success response with data
const users = await getUsers();
return responses.jsonSuccess(users);

// Error responses
if (!isValidInput(data)) {
  return responses.badRequest('Invalid input data');
}

if (!isAuthenticated(user)) {
  return responses.unauthorized('Authentication required');
}

if (!hasPermission(user, 'read')) {
  return responses.forbidden('Insufficient permissions');
}

// No content response
await deleteUser(userId);
return responses.noContent();

Individual Imports:

import { jsonSuccess, badRequest, serverError } from '@timmons-group/snack-utils/responses';

// Use specific response functions
export const handler = async (event) => {
  try {
    const data = await processRequest(event);
    return jsonSuccess(data);
  } catch (error) {
    if (error.code === 'VALIDATION_ERROR') {
      return badRequest(error.message);
    }
    return serverError('An unexpected error occurred');
  }
};

Custom Response Headers:

import { jsonSuccess } from '@timmons-group/snack-utils/responses';

// The responses automatically include CORS headers and Content-Type
const response = jsonSuccess({ message: 'Success' });
// Returns:
// {
//   statusCode: 200,
//   headers: {
//     'Content-Type': 'application/json',
//     'Access-Control-Allow-Origin': '*',
//     'Access-Control-Allow-Headers': 'Content-Type',
//     'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
//   },
//   body: '{"message":"Success"}'
// }

Complete Example

import { createLoggers } from '@timmons-group/snack-utils/logger';
import { createProfiler } from '@timmons-group/snack-utils/profiler';
import { responses } from '@timmons-group/snack-utils/responses';

const { log, error } = createLoggers('UserAPI');

export const handler = async (event) => {
  const profiler = createProfiler();
  
  try {
    log('Processing user request');
    
    profiler.tab('Input Validation');
    const { userId } = JSON.parse(event.body);
    if (!userId) {
      return responses.badRequest('User ID is required');
    }
    
    profiler.tab('Database Query');
    const user = await getUserById(userId);
    if (!user) {
      return responses.notFound('User not found');
    }
    
    profiler.tab('Response Generation');
    const response = responses.jsonSuccess(user);
    
    profiler.end();
    profiler.report();
    
    return response;
    
  } catch (err) {
    error('Request failed:', err.message);
    return responses.serverError('Internal server error');
  }
};

Environment Variables

  • LOG_LEVEL - Controls logging verbosity (ERROR, WARN, INFO)

Exports

// All utilities
import { createLoggers, setLogLevel, createProfiler, responses } from '@timmons-group/snack-utils';

// Individual utilities
import { createLoggers } from '@timmons-group/snack-utils/logger';
import { createProfiler } from '@timmons-group/snack-utils/profiler';
import { responses, jsonSuccess } from '@timmons-group/snack-utils/responses';

Best Practices

  1. Create Module Loggers: Use descriptive module names for better log organization
  2. Profile Critical Paths: Use profiler for performance-sensitive operations
  3. Consistent Responses: Use response utilities for uniform API responses
  4. Environment-based Logging: Set appropriate log levels for different environments
  5. Error Handling: Always use proper HTTP status codes for different error scenarios

Roadmap

  • [x] Logger with multiple levels
  • [x] Performance profiler
  • [x] HTTP response utilities
  • [x] CORS support
  • [ ] Structured logging (JSON format)
  • [ ] Log aggregation support
  • [ ] Metrics collection
  • [ ] Request tracing
  • [ ] Response caching utilities