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

@ritts/auth-starter

v1.0.9

Published

Plug-and-play authentication for Express apps — signup, signin, JWT, MongoDB, Zod validation

Downloads

61

Readme

auth-starter

Plug-and-play authentication for Express.js apps.
Ships with signup, signin, JWT protection, MongoDB/Mongoose, and Zod input validation — all in ES Modules.


Features

  • User signup with hashed passwords (bcryptjs)
  • User signin with JWT token response
  • GET /auth/me — fetch the logged-in user
  • Zod validation on all inputs (clear error messages)
  • authMiddleware to protect any route in your app
  • connectDB helper to connect to MongoDB

Requirements

  • Node.js 18+
  • Express 4 or 5
  • A MongoDB database (local or MongoDB Atlas)

Installation

npm install auth-starter

Install Express and dotenv in your own project if you haven't already:

npm install express dotenv

Quick Start

1. Create a .env file in your project root

MONGO_URI=mongodb://localhost:27017/myapp
JWT_SECRET=your_super_secret_key_change_this_in_production
JWT_EXPIRES_IN=7d

Never commit your .env file. Add it to .gitignore.


2. Set up your Express app

// app.js
import "dotenv/config";
import express from "express";
import { connectDB, authRouter } from "auth-starter";

const app = express();

// Parse incoming JSON
app.use(express.json());

// Connect to MongoDB
await connectDB(process.env.MONGO_URI);

// Mount auth routes at /auth
app.use("/auth", authRouter);

// Your own routes below...
app.get("/", (req, res) => res.send("Hello World"));

app.listen(3000, () => console.log("Server running on port 3000"));

Make sure your package.json has "type": "module" to use ES Modules.


Auth Routes

All routes are mounted wherever you call app.use('/auth', authRouter).

POST /auth/signup

Register a new user.

Request body:

{
  "name": "John Doe",
  "email": "[email protected]",
  "password": "secret123"
}

Success response (201):

{
  "success": true,
  "message": "Account created successfully",
  "token": "eyJhbGci...",
  "user": {
    "id": "664abc...",
    "name": "John Doe",
    "email": "[email protected]"
  }
}

Validation error (400):

{
  "success": false,
  "errors": {
    "email": ["Invalid email address"],
    "password": ["Password must be at least 6 characters"]
  }
}

POST /auth/signin

Sign in with email and password.

Request body:

{
  "email": "[email protected]",
  "password": "secret123"
}

Success response (200):

{
  "success": true,
  "message": "Signed in successfully",
  "token": "eyJhbGci...",
  "user": {
    "id": "664abc...",
    "name": "John Doe",
    "email": "[email protected]"
  }
}

Invalid credentials (401):

{
  "success": false,
  "message": "Invalid email or password"
}

GET /auth/me (protected)

Get the currently authenticated user. Requires a valid JWT in the Authorization header.

Request headers:

Authorization: Bearer <your_token>

Success response (200):

{
  "success": true,
  "user": {
    "_id": "664abc...",
    "name": "John Doe",
    "email": "[email protected]",
    "createdAt": "2024-01-01T00:00:00.000Z"
  }
}

Protecting Your Own Routes

Use authMiddleware on any route you want to lock behind authentication.

import { authMiddleware } from 'auth-starter';

// Single route
app.get('/dashboard', authMiddleware, (req, res) => {
  res.json({ message: `Hello user ${req.user.userId}` });
});

// Router group
import { Router } from 'express';
const router = Router();
router.use(authMiddleware); // protects ALL routes in this router

router.get('/profile', (req, res) => { ... });
router.put('/settings', (req, res) => { ... });

After the middleware runs, req.user contains:

{
  userId: "664abc..."; // MongoDB _id of the logged-in user
}

API Reference

connectDB(mongoUri)

Connects to MongoDB. Call this once before starting your server.

import { connectDB } from "auth-starter";

await connectDB(process.env.MONGO_URI);

| Parameter | Type | Description | | ---------- | ------ | ------------------------------ | | mongoUri | string | Your MongoDB connection string |

Throws if mongoUri is missing or the connection fails.


authRouter

An Express Router with three routes pre-configured:

| Method | Path | Description | | ------ | --------- | ------------------ | | POST | /signup | Register new user | | POST | /signin | Login, returns JWT | | GET | /me | Get current user |

Mount it with:

app.use("/auth", authRouter); // routes become /auth/signup, /auth/signin, /auth/me
app.use("/api/auth", authRouter); // or any prefix you like

authMiddleware

Express middleware that verifies the JWT from the Authorization: Bearer <token> header.

On success: adds req.user = { userId } and calls next().
On failure: responds 401 with { success: false, message: "..." }.


Environment Variables

| Variable | Required | Default | Description | | ---------------- | -------- | ------- | ----------------------------- | | MONGO_URI | Yes | — | MongoDB connection string | | JWT_SECRET | Yes | — | Secret key for signing JWTs | | JWT_EXPIRES_IN | No | 7d | JWT expiry (e.g. 1h, 30d) |


Full Project Example

my-project/
├── .env
├── package.json        ← must have "type": "module"
├── app.js
└── routes/
    └── posts.js
// app.js
import "dotenv/config";
import express from "express";
import { connectDB, authRouter } from "auth-starter";
import postsRouter from "./routes/posts.js";

const app = express();
app.use(express.json());

await connectDB(process.env.MONGO_URI);

app.use("/auth", authRouter);
app.use("/posts", postsRouter); // your own routes

app.listen(3000);
// routes/posts.js
import { Router } from "express";
import { authMiddleware } from "auth-starter";

const router = Router();

router.get("/", (req, res) => res.json({ posts: [] })); // public
router.post("/", authMiddleware, (req, res) => {
  // protected
  res.json({ message: `Post created by ${req.user.userId}` });
});

export default router;

License

MIT