next-on-pages icon indicating copy to clipboard operation
next-on-pages copied to clipboard

[🐛 Bug]: 500 Error when wrapping api routes with custom logic

Open josephp27 opened this issue 1 year ago • 12 comments

next-on-pages environment related information

No response

Description

Summary

Is there a way to do what I am doing below? The issue is if i throw a non standard error, it will error 500 even though I am catching. It will completely skip over the entire catch statement. What's weirder is this works locally, but when I deploy, it doesn't. This also works on vercel, so I'm guessing it's somehow related to how pages dedups code?

class NotAuthorizedException extends Error {
  constructor(message?: string) {
    super(message);
    this.name = "NotAuthorizedException";
  }
}

// user is injected here
async function GET(request: NextRequest, args, user: User): Promise<Response> {
  // i can throw custom exceptions here and handle them in the wrapper. this should throw a 401, but doesn't
  throw new NotAuthorizedException("This is a custom error");
}

type Handler<T, R> = (req: NextRequest, ctx: T) => Promise<R>;

const withAuth = <T, R>(handler: Handler<T, R>) => {
  return async (req: NextRequest, ctx: T): Promise<Response | R> => {
    // inject user information here
    return handler(req, ctx, user).catch((error) => {
      // depending on the error code return a response
      if (error instanceof NotAuthorizedException) {
        return new Response("Not authorized", { status: 401 });
      }
      return new Response("Internal server error", { status: 500 });
    });
  };
};

export default withAuth(GET);

Additional information

No response

Example

No response

Reproduction

No response

Pages Deployment Method

None

Pages Deployment ID

No response

Additional Information

No response

Would you like to help?

  • [ ] Would you like to help fixing this bug?

josephp27 avatar Jan 23 '24 03:01 josephp27

Another example that should return a 401, but gives a 500. again this works locally and on vercel, but not on cloudflare pages:

const GET = async (req: NextRequest) =>
  await withAuthv2(req, async () => {
    throw new NotAuthorizedException("Not authorized");
  });

type Handler = () => Promise<Response>;

const withAuthv2 = async (
  _req: NextRequest,
  handler: Handler
): Promise<Response> => {
  return handler().catch((error) => {
    if (error instanceof NotAuthorizedException) {
      return new Response("Not authorized", { status: 401 });
    }
    return new Response("Internal server error", { status: 500 });
  });
};

export default GET;

Logs:

  "logs": [
    {
      "message": [
        "Error: An error occurred while evaluating the target edge function (__next-on-pages-dist__/functions/api/limits.func.js)"
      ],
      "level": "error",
      "timestamp": 1706076467204
    }
  ],

josephp27 avatar Jan 24 '24 06:01 josephp27

This happens on "next": "^14.0.4",

i reverted to "next": "13.1.5", and do not have this issue

josephp27 avatar Jan 24 '24 07:01 josephp27

Hello @josephp27, I have tried to reproduce this error using your second code snippet with both the app directory and the pages directory, but did not have any luck with the latest Next.js v14.1.0.

Please can you try with the latest version of Next.js and see if this error is still happening for you?

james-elicx avatar Feb 03 '24 22:02 james-elicx

Idk if my case related with next-on-pages or not. I've got this error with wrangler pages dev, but work perfectly with normal next start. I am using Hono for the handler.

[wrangler:inf] GET /api/health/ping 500 Internal Server Error (117ms)

ERROR] ReferenceError: async__chunk_8073 is not defined
at 2991
  (file:///home/yb/Developers/nodejs/mutato/.vercel/output/static/_worker.js/__next-on-pages-dist__/functions/api/[[...route]].func.js:21:56166)
      at q
...

Response with next start

next start

   ▲ Next.js 14.1.3
   - Local:        http://localhost:3000

 ✓ Ready in 1826ms
  <-- GET /api/health/ping
  --> GET /api/health/ping 200 244ms

yarabramasta avatar Mar 18 '24 05:03 yarabramasta

Would you be able to share a reproduction @yarabramasta?

james-elicx avatar Mar 18 '24 08:03 james-elicx

@james-elicx I don't have time to reproduce from scratch, here is a copy of the mentioned problem https://github.com/yarabramasta/mutato/tree/1f7dd7b91fff0f8a86131456fb1c7918060f9332 under folder src/server. thanks!

yarabramasta avatar Mar 18 '24 09:03 yarabramasta

Hey all - I'm also receiving this on a page route after upgrading to Next.js 14 from 13. It's interesting because the page is served correctly, without any issues apparent to the user, but the HTTP status is 500, and logs show an error like: ReferenceError: async__chunk_XXXX is not defined

Any further progress on resolving this?

AlecKriebel avatar Jun 27 '24 16:06 AlecKriebel

Hey all - I'm also receiving this on a page route after upgrading to Next.js 14 from 13. It's interesting because the page is served correctly, without any issues apparent to the user, but the HTTP status is 500, and logs show an error like: ReferenceError: async__chunk_XXXX is not defined

Any further progress on resolving this?

Confirming that reverting to Next.js 13, without any other changes, fixed this issue for me.

AlecKriebel avatar Jun 28 '24 15:06 AlecKriebel

@AlecKriebel do you have a reproduction by any chance? The repo the other user linked doesn't exist. I think this should probably be done in a separate issue as well.

james-elicx avatar Jul 12 '24 17:07 james-elicx

I am also encountering this problem on next@^14 and when following hono's documentation for Vercel here: https://hono.dev/docs/getting-started/vercel

I get 500s with async__chunk_128 errors as the posters above.

This does not occur when I downgrade to next@^13

i3dly avatar Oct 12 '24 22:10 i3dly

Alright, I was able to resolve this for my case specifically. In case you are interested @james-elicx , I was importing this package: https://www.npmjs.com/package/@paralleldrive/cuid2, which was causing the async__chunk_128 errors on next@^14, but not on next@^13. I've forked the cuid package and removed the parts I didn't need which got rid of the errors for me.

My current guess (which I haven't validated), is that if there is a reference to global or window on an api route (which this cuid package has here), it causes next-on-pages to emit these errors.

i3dly avatar Oct 13 '24 00:10 i3dly

Alright, I was able to resolve this for my case specifically. In case you are interested @james-elicx , I was importing this package: https://www.npmjs.com/package/@paralleldrive/cuid2, which was causing the async__chunk_128 errors on next@^14, but not on next@^13. I've forked the cuid package and removed the parts I didn't need which got rid of the errors for me.

My current guess (which I haven't validated), is that if there is a reference to global or window on an api route (which this cuid package has here), it causes next-on-pages to emit these errors.

I also encountered this problem in one api route which imported cuid2, although this caused no errors in another api route which also used cuid2. My solution was to wrap createId in another function in a different file, and import and use that instead:

import { createId } from '@paralleldrive/cuid2';

export function createIdWrapper(): string {
  return createId();
}

Just putting my two cents in for anyone facing this issue because of cuid2

thiagoalbrecht avatar Nov 18 '24 00:11 thiagoalbrecht