Rewrites Not Working When Using Express With Netlify Functions

Hi Netlify Community,

When I set up rewrites for a function that uses Express they don’t seem to work. However, when typing in the full endpoint for a function that uses express I am able to get it to work.

Below is a link to my repository on GitHub. In my client folder, you can see my redirects file with the rewrite rules I implemented. In my server folder you can see two functions I set up as examples. withexpress.js uses Express and withoutexpress.js uses the regular syntax.

Hi, are you trying to run an express server? Seems like maybe you are - that won’t work.

Here is a good summary of what you can and can not do on Netlify you might find helpful:

Hi Perry,

Thank you for your reply! Yes, I am using express with my Netlify functions. I followed the tutorial on Netlify below to get everything set up. Everything for the functions works.

I am just having problems with rewriting the urls of the functions. I have two functions set up in my GitHub repository as examples. They both do the same thing. For the one that uses the regular syntax for functions it works, but for the one that uses Express I get an error unless I go to the full path of /.netlify/functions/api/withexpress. Additonally, setting up a 301 redirect works, bit I would really like to only show clean urls instead of the full endpoints for the functions.

Hey there! This is interesting. Can you please share the netlify.toml or _redirects file that works for the non-Express function? Is it this?:
https://github.com/William-Boomer-Baker/netlify-errros/blob/master/client/_redirects#L1

Just so I make sure I understand your goal correctly: you want to use redirects to make your function “endpoint” in the browser be something like “/listOfItems” instead of “/.netlify/functions/listOfItems”?

Hi Jen,

Thank you for your reply! Yes, my goal would be to have something like “/listOfItems” instead of “/.netlify/functions/listOfItems.

Also, yes, that is my redirects file. I set it up like that to show how I am doing the same thing for both, but only the function that doesn’t use express seems to actually rewrite the function. When I change the number to 301 there isn’t any issues. It shows the full endpoint which I don’t want. Do you know why this is and how I could fix it?

Based on this thread, it seems like it might have to do with how the express router works with our redirects:
https://answers.netlify.com/t/redirect-to-function-not-working/4453/7

Want to try changing your app.use function as described in that thread and see if that fixes things for you?

I believe you’ll also need to update your router.get path to be /withexpress :slight_smile: Fingers crossed!

Hi Jen,

Wooo that worked!! Thank you so much :smiley:

1 Like