instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
415 stars 29 forks source link

Doesn't work with native rewrites of NextJS #436

Closed abriginets closed 2 years ago

abriginets commented 2 years ago

Describe the bug For some reason it is possible to rewrite request path to next-api-decorators but it's reading the old path instead of rewritten one.

To Reproduce Create match-all slug under pages/api/[[...slug]].ts and then create a rewrite rule in NextJS config:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return {
      beforeFiles: [
        {
          source: '/assets/image/airline/:type/:width/:iata.:extension',
          destination: '/api/image/airline/type/:type/width/:width/code/:iata/extension/:extension',
        },
      ],
    };
  },
};

module.exports = nextConfig;

Try to access the /assets/image/airline/:type/:width/:iata.:extension path and you'll see the error

{"statusCode":404,"message":"Cannot GET /assets/image/airline/al_square/500/SU.webp","error":"Not Found"}

So it seems like rewrite was successfully applied but next-api-decorators are reading the original url path instead of new one.

Expected behavior It should read the new path that was applied after rewrite.

abriginets commented 2 years ago

There is a metadata on request object

  [Symbol(NextRequestMeta)]: {
    __NEXT_INIT_URL: 'http://localhost:3000/assets/image/airline/al_square/500/S7.avif',
    __NEXT_INIT_QUERY: {},
    __nextHadTrailingSlash: undefined,
    _nextRewroteUrl: '/api/image/airline/type/al_square/width/500/code/S7/extension/avif',
    _nextDidRewrite: true
  }

But I'm not sure how to pull it out. This issue may be fixed by simply checking for it in the code

const url = (req.[...]._nextRewroteUrl || req.url).split('?')[0];
ggurkal commented 2 years ago

Hi @abriginets

A fix is release under the beta channel. Let me know if it works for you.

abriginets commented 2 years ago

@ggurkal yep. that works!

github-actions[bot] commented 2 years ago

:tada: This issue has been resolved in version 1.8.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: