Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next "catch all routes" does not work #101

Open
yakovlev-alexey opened this issue Jan 19, 2023 · 1 comment
Open

Next "catch all routes" does not work #101

yakovlev-alexey opened this issue Jan 19, 2023 · 1 comment

Comments

@yakovlev-alexey
Copy link
Contributor

This issue is a continuation of #93 and #96. Nested routes like [...slug] do not work with nest-next. Next documentation on such pages - https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes.

@lluiscab
Copy link

lluiscab commented Feb 11, 2023

I've been experimenting for two hours or so and I've come up with the following solution that seems to work correctly.
NextJS internally uses req.params when handling dynamic routes, if Nest does not parse the params exactly as Next expects them, then Next will try to render a different, potentially non-existent page

Here's my solution
app.controller.ts

  @Get('/post*')
  @Render('/post/[...slug]')
  @UseInterceptors(new CatchAllInterceptor('slug'))
  async signInStep(
    @Param('slug') slugArray: string[],
  ) {
     if (slugArray === undefined) { // No slug defined, request path is /post
       // (...)
     }

     const slug = slugArray.join('/')
     // (..)
  }

catch-all.interceptor.ts

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import express from 'express';

@Injectable()
export class CatchAllInterceptor implements NestInterceptor {
  constructor(private readonly name: string) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const request = context.switchToHttp().getRequest<express.Request>();
    const wildcardParam = request.params['0'];
    if (wildcardParam) {
      // @ts-expect-error request.params does not expect values to be of type string[], but Next does
      request.params = { [this.name]: wildcardParam.split('/') };
    }

    return next.handle();
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants