next.jsrelay

How can we get Relay to work in production with NextJS?


I have a NextJS project using Relay. I have it working fine in development, but when I build, it is building static pages and is trying to access my GraphQL server (in dev it is pointed to https://localhost:3000/api/graphql), but I don't want it to since it should be a dynamic page.

With that, I also can't seem to get SSR working with Relay since a lot of functionality in Relay requires hooks and we can't use hooks in non React components (like getServerSideProps()). I got as far as using loadQuery from Relay in getServerSideProps but now my issue is that I need to get the Relay environment somehow, but again, can't use getRelayEnvironment() in there either. I import it from the createRelayEnvironment file but then I'm not using my App's environment (RelayEnvironmentProvider at the root of my App).

Anyone have success with using Relay in NextJS?


Solution

  • I don't know how I missed this, but I followed along with NextJS's example for using Relay Modern on GitHub.

    I didn't do everything the same - I don't have a .babelrc file, for example, because that info is in the next.config.js file (thanks to NextJS 12.1).

    What I really used from here was how they were starting and using relay in their relay.js file. Then I used that in a getServerSideProps function in my page just like how they did in their index.js file.