Get current route in Next.js API route

Viewed 587

I want to access my current route (eg /[user_id]/posts) for both regular pages and APIs, so that I can log it in errors, increase page hit counters, etc.

The only automated way I found to retrieve the current route involves useRouter, but that is only accessible in React components.

I want to avoid hardcoding a route in each of my handlers as that can get out of sync easily.

How can I automate retrieving the current route inside a handler?

1 Answers

It's simply not supported by the framework. There are 2 alternatives I found:

1/ Use another framework such as Nest.js. With Nest, you can access router information in an interceptor. E.g. with the Fastify adapter:

@Injectable()
export class InstrumentationInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    return next.handle().pipe(
      tap(() => {
        const ctx = context.switchToHttp();
        console.log(ctx.getRequest().routerPath);
      }),
    );
  }
}

2/ Create your own controller infrastructure and attach metadata to each controller, e.g.:

export class UserController extends BaseController {
  getRoute(): string {
    return "/user/:userid";
  }
}

Note that you will need to manually keep routes in sync with your file structure. The above can be coded via Decorators too.

3?/ Theoretically you can configure a Custom Server in Nest and use a router that supports retrieving route paths, with a hook for you to retrieve the route (e.g. attach it to the request object during a middleware). If you find yourself doing this though, take a look at 1/.

Related