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.62k stars 65 forks source link

Remove necessity for next to always be defined when using .run #215

Open sf185127 opened 1 year ago

sf185127 commented 1 year ago

It is possible to hit a scenario where there is no "next" function but if I want to have universal middleware it gets an invalid function back from next-connect when i try to call it.

IE:

const withGlobal = () =>
  createRouter().use(async (req, res, next) => {
    const nextResults = next ? await next() : undefined;
    return {
      ...nextResults,
      props: { ...nextResults?.props, global: { yo: "yo" } },
    };
  });

and in the page i have

export const getServerSideProps = async (ctx: GetServerSidePropsContext) =>
  await createRouter()
    .use(withGlobal())
    .run(ctx.req, ctx.res);

Running this throws TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

which i traced back to this file in Router.exec line 80 it expects there to be a function inside fns at ++i but since i'm using run (and not a get or post handler) i shouldnt need to add anymore fns on the end of this.

FYI

export const getServerSideProps = async (ctx: GetServerSidePropsContext) =>
  await createRouter()
    .use(withGlobal())
    .use(() => ({}))
    .run(ctx.req, ctx.res);

does work because creates the fn that next() is looking for, but its ugly and idontwanna

changeset-bot[bot] commented 1 year ago

⚠️ No Changeset found

Latest commit: e8344ed72b15d0f67a94d70bb3a93aa9c77658bf

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

codecov[bot] commented 1 year ago

Codecov Report

Merging #215 (e8344ed) into main (e5ac7fa) will not change coverage. The diff coverage is 100.00%.

@@            Coverage Diff            @@
##              main      #215   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            5         5           
  Lines          436       436           
  Branches        60        60           
=========================================
  Hits           436       436           
Impacted Files Coverage Δ
src/router.ts 100.00% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more