nestjs route exclude file extensions

Viewed 147

Hi for a couple of days I have this challenge

I'm building with NestJS (https://nestjs.com/)

I want to have a route that only listens when it doesn't have a file extension.

So for example

localhost:3000 -> good
localhost:3000/ -> good
localhost:3000/test -> good
localhost:3000/test.txt -> ignore
localhost:3000/css/mycss.css -> ignore

Also, when the route is valid, I want to know the slug in the params

for example

localhost:3000/test
Get('/:slug')
params.slug = test

Can somebody help me?

1 Answers

NestJs doesn't support RegExp in the controller routes. It only accepts strings or an array of strings. Thus, you cannot set sophisticated patterns there.

The characters ?, +, *, and () may be used in a route path, and are subsets of their regular expression counterparts. The hyphen ( -) and the dot (.) are interpreted literally by string-based paths.

Source

However, you can get the request value and check it manually. If this way is okay for you then try something like this

import {Controller, Get, Req} from '@nestjs/common';
import {Request} from 'express';

@Controller()
export class AppController {
  @Get(':slug')
  test(@Req() request: Request) {
    const pattern = /[\w]+[.]+[\w]+/;
    if (pattern.test(request.url)) return 'bad';

    return 'good';
  }
}

Modify the pattern as you need. The current example considers something.txt as bad (Anything including dot is bad) but something as a good pattern.

Related