Next.js Discord

Discord Forum

Next.js is broken

Unanswered
American Black Duck posted this in #help-forum
Open in Discord
American Black DuckOP
By setting NextResponse2 = NextResponse the last call to NextResponse works, otherwise it throws an error NextResponse is not defined.
This exists only for the last call the previous ones work

try {} catching the whole function captures the error and can be returned with NextResponse (which is also ridiculous)

import { NextRequest, NextResponse } from 'next/server';
import { getSubdomain } from '@/app/utils/domains';
import { matchPath, splitPath } from '@/app/utils/paths';
import { mongoConnect } from '@/app/lib/db/mongodb';
import { ApiModel } from '@/app/models/api';

const NextResponse2 = NextResponse

async function handler(request: NextRequest, { params }: { params: Promise<{ params: string[]}> }) {
  const host = request.headers.get('host') || request.headers.get(':authority')  || '';
  const resolvedParams = await params;
  let pathArray = resolvedParams.params;

  const subdomain = getSubdomain(host);
  if (!subdomain || subdomain.length != 24) {
    return NextResponse.json({ error: `Subdomain ${subdomain} not found` }, { status: 404 });
  }

  await mongoConnect();

  const api = await ApiModel.findById(subdomain);
  if (!api) {
    return NextResponse.json({ error: `API for id ${subdomain} not found` }, { status: 404 });
  }

  for (let group of api.groups) {
    if (group.prefix != "" && pathArray.length == 0) {
      continue
    }

    const [prefix, ...rest] = pathArray;
    pathArray = rest;

    if (group.prefix != prefix) {
      continue
    }

    for (let resource of group.resources) {
      if (!resource.methods.some((method: string) => method == request.method)) {
        continue
      }
      
      const resourcePath = splitPath(resource.path);
      const [isMatch, pathParams] = matchPath(resourcePath, pathArray);
      if (!isMatch) {
        continue
      }
      return NextResponse.json({data: resource.data});
    }
  }
  
  return NextResponse2.json({ error: `No matching resource for path ${pathArray}` }, { status: 404 });
}

export const GET = handler;
export const POST = handler;
export const PUT = handler;
export const DELETE = handler;
export const PATCH = handler;
export const OPTIONS = handler;
export const HEAD = handler;

0 Replies