@ev-fns/auth

Authorization middleware for expressjs

Usage no npm install needed!

<script type="module">
  import evFnsAuth from 'https://cdn.skypack.dev/@ev-fns/auth';
</script>

README

@ev-fns/auth

Authorization middleware for expressjs

  • createAuth createAuth: ({ token, getToken }: { token: string, getToken?: (req: express.Request) => string }) => express.RequestHandler

version node downloads dependencies

Install

yarn add express @ev-fns/auth

Usage

const express = require("express");
const { createAuth } = require("@ev-fns/auth");

const app = express();

const auth = createAuth({ token: process.env.API_TOKEN });

app.get("/", auth, (req, res) => {
  res.status(200).json({ message: "Hello World 👋!" });
});

app.use((err, req, res, next) => {
  res.status(err.status || 500).json({ message: err.message });
});

app.listen(3000, () => {
  console.log("listening at http://localhost:3000");
});

Try it out

$ API_TOKEN=super_secret node index.js
  1. Invalid request

    $ curl -i http://localhost:3000
    
    HTTP/1.1 401
    ...
    {"message":"Unauthorized"}
    
  2. Valid request

    $ curl -i -H "Authorization: Bearer super_secret" http://localhost:3000
    
    HTTP/1.1 200
    ...
    {"message":"Hello World 👋!"}