How to handle unmatched routes with serverless

anjantalatam

Anjan Talatam

Posted on October 21, 2023

How to handle unmatched routes with serverless

Context:

I mistakenly misspelled my login route as /dev/loginn instead of /dev/login on Postman, here is the response

{
    "currentRoute": "post - /dev/loginn",
    "error": "Serverless-offline: route not found.",
    "existingRoutes": [...],
    "statusCode": 404
}
Enter fullscreen mode Exit fullscreen mode

Problem

The above response has 2 major issues

  1. Existing routes are getting exposed which shouldn't be (ideally).
  2. The response is too detailed. We need to keep it simple.

Fix

Add a new Lambda function to handle unmatched/ unconfigured Routes in serverless.yml

#serverless.yml

functions:
  unmatchedRoute:
    handler: handler.unmatchedRoute
    events:
      - http:
          path: /{proxy+}
          method: ANY
Enter fullscreen mode Exit fullscreen mode
// handler.ts

import { Handler } from 'aws-lambda';

export const unmatchedRoute: Handler = async () => {
  return {
    statusCode: 404,
    body: '404 page not found',
  };
};
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! Drop a like if you found it helpful ❤️

Cheers! Anjan Talatam


Ignore from here

SEO

  1. How to handle unconfigured routes with serverless
  2. How to handle unmatched routes for AWS lambda functions
  3. How to handle unconfigured routes for AWS lambda functions
  4. How to handle unconfigured routes for AWS lambda functions with serverless
💖 💪 🙅 🚩
anjantalatam
Anjan Talatam

Posted on October 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related