How to link Gatsby.js with my Express server How to link Gatsby.js with my Express server express express

How to link Gatsby.js with my Express server


Add this to your Gatsby-config file

module.exports = {  proxy: {    prefix: "/users",    url: "http://localhost:3000",  },}

This way, when you fetch('/users/todos') in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:3000/users/todos as a fallback.


In development you need to add to your gatsby-config.js the proxy-middleware as others have said. In production will be totally dependent on where you are running/hosting the Gatsby project.Is your project self-hosted? It depends on what HTTP web server you are running. Nginx for example: you need to open the Nginx configuration file and create a block that allows calls to find your express server on port 3000 (http://nginx.org/en/docs/beginners_guide.html)

location /api {proxy_set_header 'Access-Control-Allow-Origin' 'http://xxx.xxx';proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';proxy_set_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type,Origin';proxy_pass http://127.0.0.1:3000;proxy_redirect off;proxy_buffering on;proxy_set_header    Host                        $host;proxy_set_header    X-Real-IP               $remote_addr;proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header    origin                  `http://xxx.xxx';}

This example is from https://www.rodrigoplp.com/blog/using-your-own-server-with-gatsby


I had this exact same problem, and solved it by following the advice under "Advanced Proxying" on the GatsbyJS website:

https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying

My suggestion to you is that you modify your gatsby-config.js (not the package.json) file to the following:

var proxy = require("http-proxy-middleware")module.exports = {  developMiddleware: app => {    app.use(      proxy({        target: "http://localhost:3000",      })    )  },}

You might need to create the gatsby-config.js file. You also might need to remove the "proxy" line from your package.json file.