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 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-ez

v1.0.6

Published

Express Middleware Toolkit for Error Handling, Auth, Rate Limiting, and More

Readme

express-ez 🚀

Express Middleware Toolkit for Error Handling, Auth, Rate Limiting, and More


Features

Error HandlingasyncHandler + AppError
AuthenticationauthGuard + signCookie
Rate LimitingcreateRateLimiter
ValidationvalidateRequest with Zod
ResponsessendResponse with consistent formatting


Installation

npm install express-ez
# or
yarn add express-ez

Usage

1. Error Handling

asyncHandler

Wrap async routes to auto-catch errors:

const { asyncHandler } = require('express-ez');

app.get('/data', asyncHandler(async (req, res) => {
  const data = await fetchData();
  sendResponse(res, { data });
}));

AppError

Throw structured errors:

const { AppError } = require('express-ez');

throw new AppError(404, 'User not found', { userId: 123 });
// => { statusCode: 404, message: 'User not found', data: { userId: 123 } }

2. Authentication

authGuard

Protect routes with JWT:

const { authGuard } = require('express-ez');

app.get('/profile', authGuard, (req, res) => {
  sendResponse(res, { data: req.auth }); // req.auth = decoded JWT
});

signCookie

Set secure auth cookies:

const { signCookie } = require('express-ez');

app.post('/login', (req, res) => {
  const token = signCookie(res, { userId: 123 }, { 
    name: 'auth_token', 
    cookieOptions: { sameSite: 'Strict' } 
  });
});

3. Rate Limiting

createRateLimiter

Customize rate limits per route:

const { createRateLimiter } = require('express-ez');

const strictLimiter = createRateLimiter({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 10, // 10 requests per window
  message: 'Too many attempts. Try again later.'
});

app.post('/login', strictLimiter, authController);

4. Validation

validateRequest

Validate requests with Zod:

const { z } = require('zod');
const { validateRequest } = require('express-ez');

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8)
});

app.post('/login', validateRequest(loginSchema), (req, res) => {
  // req.body is now validated!
});

5. Responses

sendResponse

Consistent JSON responses:

const { sendResponse } = require('express-ez');

app.get('/success', (req, res) => {
  sendResponse(res, { 
    statusCode: 200, 
    data: { key: 'value' },
    message: 'Custom success message' 
  });
});

// Output:
// { success: true, status: 200, message: "...", data: { ... } }

6. Authorization

authorize

Role-based access control:

const { authorize } = require('express-ez');

const adminOnly = authorize(['admin']);
app.delete('/users/:id', authGuard, adminOnly, (req, res) => {
  // Only admins can reach here
});

7. Messages & Constants

Pre-defined HTTP messages:

const { httpStatus, messages } = require('express-ez');

console.log(httpStatus.NOT_FOUND); // 404
console.log(messages.UNAUTHORIZED); // "You are not logged in"

8. Request ID Middleware

Automatically adds a unique X-Request-ID header to each request for tracing:

const { requestId } = require('express-ez');

// Basic usage (default 16-byte ID)
app.use(requestId());

// Custom ID length (e.g., 8 bytes)
app.use(requestId(8));

Behavior:

  • Generates a cryptographically random hex ID (e.g., X-Request-ID: a1b2c3d4e5f6)
  • Works with asyncHandler for error propagation
  • Compatible with tracing systems (Datadog, OpenTelemetry)

Example Output:

HTTP/1.1 200 OK
X-Request-ID: 7b3f8e2a9d0c4f61

Advanced Configuration

Customizing Defaults

const { env } = require('express-ez');

// Override JWT settings at startup
env.defaults.JWT_SECRET = 'my_new_secret';
env.defaults.MAX_AGE = 48;

Examples

Full Auth Flow

const { 
  asyncHandler, 
  authGuard, 
  signCookie, 
  validateRequest 
} = require('express-ez');

app.post(
  '/login',
  validateRequest(loginSchema),
  asyncHandler(async (req, res) => {
    const user = await loginUser(req.body);
    signCookie(res, { userId: user.id });
    sendResponse(res, { data: user });
  })
);

app.get('/profile', authGuard, (req, res) => {
  sendResponse(res, { data: req.auth });
});

Why Choose express-ez?

  • Zero Boilerplate: Sane defaults for quick setup.
  • Flexible: Customize everything (cookies, rate limits, errors).

Contributing

PRs welcome! See GitHub.


License

MIT © Brijesh GP