hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.63k stars 65 forks source link

possible to use with serverless-http? #107

Closed parkan closed 3 years ago

parkan commented 3 years ago

Hello, I'm trying to find a lightweight way to use middlewares and method-based dispatch (for REST) with netlify functions, and it seems like next-connect could be promising for this use. Because netlify functions use AWS lamba style handlers with a APIGatewayEvent, Context signature, it seems that we need to use an adapter like serverless-http to make the two work together, similar to how you'd use express in a function context.

However, something doesn't seem to be working, as I am getting this error:

◈ Error during invocation:  {
  errorMessage: 'r is not a constructor',
  errorType: 'TypeError',
  stackTrace: [
    'e.exports (/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:3334)',
    'Module.<anonymous> ' +
      '(/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:4541)',
    'Module.<anonymous> ' +
      '(/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:4645)',
    'n (/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:158)',
    '/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:957',
    'Object.<anonymous> ' +
      '(/home/arkadiy/slushie-mvp-api/dist/api/contributor.js:1:966)',
    'Module._compile (internal/modules/cjs/loader.js:774:30)',
    'Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)',
    'Module.load (internal/modules/cjs/loader.js:641:32)',
    'Function.Module._load (internal/modules/cjs/loader.js:556:12)'
  ],

This seems to come up a lot in various framework contexts, but unfortunately I haven't been able to find any post that actually explains what it means.

The code here is just the minimal nc().post(... then wrap handler with serverless

Any idea what could be going awry? One guess is that polymorphic function with 2 args (i.e. without path arg) could be an issue.

hoangvvo commented 3 years ago

I look into serverless-http source code and it seems like it might have incorrectly determined the framework that is being used. According to get-framework.js, it will try to call nc.handle even though that is not the right one.

Can you try something like this:

// insteadof serverless(handler)
serverless((req, res) => handler(req, res))
hoangvvo commented 3 years ago

The above snippet should work