express-route-config
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

Express route config

A simple route configuration for Express apps powered by Typescript typing.

Greenkeeper badge Travis codecov Dev Dependencies

About

The motivation is to provide a simple util for role based authentication. It's a common scenario in web apps that some routes are public, allowed only for authentication users or only for admins.

Getting Started

npm install express-route-config
yarn add express-route-config

Example

import passport from 'passport';
import { loadRoutes } from 'express-route-config';
 
const app = express();
const router = Router();
 
type UserRole = 'user' | 'admin' | 'reporter';
 
loadRoutes<UserRole>({
  // use any ExpressJS middleware for authentication
  // The middleware should set `req.user` if authentication was successful.
  authMiddleware: passport.authenticate('bearer', { session: false }),
  router,
  hasRole: (req, role) => req.user.role === role,
  isLoggedIn: req => req.user != null,
  routes: {
    '/public': {
      get: {
        method: handler,
        public: true,
      },
    },
    '/public2': {
      get: {
        // method can be any valid handler/middleware used in Express
        method: [handler, handler2, handler3],
        public: true,
      },
    },
    '/auth': {
      get: {
        method: handler,
      },
    },
    '/admin-only': {
      get: {
        method: handler,
        // roles must be UserRole
        // an error will be reported if there is any typo
        roles: 'admin',
      },
    },
    '/any-roles': {
      get: {
        method: handler,
        roles: ['user', 'admin'],
      },
    },
  },
});
 
app.use('/', router);
 
// in types/index.ts
// extend the Request object to include a `user` property.
declare global {
  namespace Express {
    interface Request {
      user: {
        id: string;
        role: UserRole
      };
    }
  }
}
 
// or if you install @types/passport
declare global {
  namespace Express {
    interface User {
      id: string;
      role: UserRole;
  }
}
 

Docs

API Reference

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i express-route-config

Weekly Downloads

1

Version

0.1.2

License

MIT

Unpacked Size

14 kB

Total Files

15

Last publish

Collaborators

  • lsentkiewicz