opennextjs / opennextjs-aws

Open-source Next.js adapter for AWS
https://opennext.js.org
MIT License
4.14k stars 126 forks source link

basePath does not works as expected with API routes #522

Closed socsieng closed 1 month ago

socsieng commented 1 month ago

Issue

NextJS app deployed using SST and OpenNext does not respect basePath property defined in NextJS config for API routes.

I'd love to work on this but unfortunately I don't know where to start.

Potentially related to: https://github.com/sst/open-next/issues/508

Environment

Reproduction steps

Clone repository at https://github.com/socsieng/next-sst which includes detailed reproduction steps. Reproduction steps also included inline.

1. create-next-app and initialize SST

npx create-next-app@latest next-sst

cd next-sst
sst init

2. Update the next.config.mjs file to include the basePath

/** @type {import('next').NextConfig} */
const nextConfig = {
  basePath: '/base-path',
};

export default nextConfig;

3. Add an API route at app/api/hello/route.ts

import { NextRequest, NextResponse } from "next/server";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function GET(request: NextRequest) {
  return NextResponse.json({ message: "Hello world!" });
}

4. Use latest version of ope-next in sst.config.ts

3.1.3 at the time of writing.

/// <reference path="./.sst/platform/config.d.ts" />

export default $config({
  app(input) {
    return {
      name: "next-sst",
      removal: input?.stage === "production" ? "retain" : "remove",
      home: "aws",
    };
  },
  async run() {
    new sst.aws.Nextjs("MyWeb", {
      openNextVersion: "3.1.3"
    });
  },
});

5. Deploy the app

sst deploy --stage api-test

6. Open the following URLs in the browser

  1. https://assignedhost.cloudfront.net/base-path
  2. https://assignedhost.cloudfront.net/base-path/api/hello

Replace assignedhost with the actual CloudFront distribution URL.

Expected results

Both 6.1 and 6.2 return successful responses.

Actual results

6.1 returns a successful response, but 6.2 returns a 404 error. Note that changing the URL for 6.2 to exclude the basePath (https://assignedhost.cloudfront.net/api/hello) works.

Note that this works as expected with sst dev:

  1. http://localhost:3000/base-path
  2. http://localhost:3000/base-path/api/hello
conico974 commented 1 month ago

It should be a pretty easy fix, we probably just need to append the basePath if necessary here https://github.com/sst/open-next/blob/388b4e70824c08aaecd19b405611d23fba741b93/packages/open-next/src/core/routingHandler.ts#L147-L149

socsieng commented 1 month ago

@conico974, I assume no one is working on this. I'll raise a PR.