Request Graphql api running on different port from Next.js app in development mode localhost

2.7k views Asked by At

I'am currently switching my existing app from create-react-app to next.js, everything seems to work correctly except my api end point running on another node app on port 4000, which i can't access from my next.js app. I followed the examples in the repo but i can't make it work, In production i use nginx as reverse proxy with no problem , but i'am in dev mode . For setting up Apollo with Redux i followed this example :with-apollo-and-redux and for proxy i used this example with-custom-reverse-proxy

I know , am making something wrong, i just can't figure it out at the moment

in the initApollo.js

...    
function create() {
      return new ApolloClient({
        ssrMode: !process.browser,
        networkInterface: createNetworkInterface({
          uri: "/api" 
        })
      });
    }
...

in server.js

...    
const devProxy = {
      "/api/": {
        target: "http://localhost:4000/api/",
        changeOrigin: true
      }
    };

    app
      .prepare()
      .then(() => {
        const server = express();

        if (dev && devProxy) {
          const proxyMiddleware = require('http-proxy-middleware')
          Object.keys(devProxy).forEach(function (context) {
            server.use(proxyMiddleware(context, devProxy[context]))
          })
        }

        server.all("*", (req, res) => handle(req, res));

        server.listen(3000, err => {
          if (err) throw err;
          console.log("> Ready on http://localhost:3000");
        });
      })
      .catch(ex => {
        console.error(ex.stack);
        process.exit(1);
      });
1

There are 1 answers

0
devoka On

Ok i finally found the problem which, is NOT related to Next.js or Apollo client. but instead it's all about my server running on port 4000 (my graphql server). i had to deal with CORS, and the express middlware express-graphql which i think it's not supported by default .

so i add the following to my server running graphql

app.use("/api", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, Content-Length, X-Requested-With"
  );
  if (req.method === "OPTIONS") {
    res.sendStatus(200);
  } else {
    next();
  }
});

and also in the apollo client i had to put absolut path to my api server

networkInterface: createNetworkInterface({
      uri: "http://localhost:4000/api/"
    })

that's it