Home
Support Forums

Serve a serverless function from root

Hi,

I’m trying to make a function handle all requests to my website. I need this because I’m working on SSR with create-react-app.

My netlify redirect config

[[redirects]]
  from = "/*"
  to = "/.netlify/functions/index"
  status = 200

Every other endpoint besides root (/) goes through the function.
I was be able to make it works locally by configuring dev to run in different port

[dev]
  command = "yarn start"
  port = 3001
  publish = "dist"

The feature is under a branch so it can be viewed via deploy-preview

Steps:

  1. Go to https://deploy-preview-1--cra-ssr.netlify.app
  2. Notice the loading indication (Client side rendering)
  3. Go to React App
  4. Notice no loading indication (Server side rendering)

Github repository: GitHub - moshfeu/cra-ssr: create-react-app + SSR
Branch: https://github.com/moshfeu/cra-ssr/tree/deploy-netlify

Thank you

Hi @moshfeu

This is because there is a file already at root (index.html) so this content is served.

Change the redirect to

[[redirects]]
  from = "/*"
  to = "/.netlify/functions/index"
  status = 200
  force = true

This will send all requests to your function even when content it found.

1 Like

Amazing!

This is because there is a file already at root

What root? Not the root of the repository. Do you mean in public or build folders?

The root (base) of the site (index.html is served by default.)

Keep in mind though, any request, to any resource, (e.g. /favicon.png, /style.css. /path/to/file) will all go to this function now as force = true so the function needs to return data for everything. I’m not sure if this is what you are wanting/intending or not.

There is a previous discussion on using a serverless function to serve on the content on base URL.

Oh, I see.

so the function needs to return data for everything

Already took it in account.

Thank you!