node.jsmiddlewarearchitect

Architect (arc.http) is not calling other handlers after middleware


I'm just trying to get started with Architect (arc.codes) and am trying to figure out how to make a shared middleware function that can be used with other routes. We have this now in serverless.js, but we're looking for alternatives.

I can confirm the middleware (auth) is running, but the fn in the index.js file never gets called. If I remove the arc.http from the get-count handler, of course, it runs my counts handler as expected. But I can't seem to get both the middleware and the handler to both run sequentially.

Here is the directory setup

tree src
src
├── http
│   └── get-counts
│       ├── index.js
└── shared
    ├── auth.js

auth.js


    const jwt = require('jsonwebtoken');
    const config = require('./utils/config.js');
    
    module.exports.handler = (req) => {
        const authorizationToken = req?.headers?.authorization;
        if (typeof authorizationToken !== 'string') {
            return {statusCode: 401}
        }
        const tokens = authorizationToken.split(' ');
        if (tokens[0] !== 'Bearer') {
            return {statusCode: 401}
        }
    
        try {
            const auth = jwt.verify(tokens[1], config.jwt.secret, {
                algorithms: [config.jwt.config.algorithm],
            });
    
            if (!auth.data.someSecurityKeyOrValue) {
                return {statusCode: 401}
            }
    
        } catch (err) {
            return {statusCode: 401}
        }
    };

get-counts/index.js

const {handler: auth} = require('@architect/shared/auth.js')
const arc = require('@architect/functions')

async function fn() {
    const body = {
        count: 42
    }
    return {
        statusCode: 200,
        headers: {
            'cache-control': 'no-cache, no-store, must-revalidate, max-age=0, s-maxage=0',
            'content-type': 'text/json; charset=utf8'
        },
        body: JSON.stringify(body)
    }
}


module.exports.handler = arc.http(auth, fn)

I've tried various returns from auth.js as is noted in the docs. But none seem to call the "next" function.

https://arc.codes/docs/en/reference/runtime-helpers/node.js#middleware

Any ideas on what I'm doing wrong?


Solution

  • It requires async or callback functions, so try making auth async:

    module.exports.handler = async (req) => {...