简体   繁体   中英

How to forward user sessions in Next.js + Graphql decoupled architecture?

I'm building a next.js project and while I usually would just use the "Custom Express Server" method to implement my graphql API (using apollo-server-express ), I thought that it might be a good idea if I decoupled the next.js project from the graphql API so that each of the servers are hosted on different machines.

But usually I would implement any session-related logic in the graphql API, using something like graphql-passport ; I figured that's good practice because if I ever choose to add another frontend (maybe a mobile app or something) they can share the same session logic. But given that I'm server side rendering content with next.js, how do I forward the user's session info to the graphql server? Because the next.js server shouldn't have to redo authentication, right?

Let me know if there are any flaws in the architecture too, I'm kind of new to this.

Using the Next server to run the GraphQL service is certainly not a good idea , so yes, do separate the two.

Letting the Next server SSR-render pages with user specific content using the users session is probably not a good idea either, unless you have some specific use case that requires the served HTML pages to have the user specific data in them already. The reasons for this are:

  • SSR rendering will require lots of server side computations since all pages always will have to be rerendered.

  • NextJS is moving away (since v9.3) from the getInitialPros() way of doing things towards using getStaticProps() to generate a page that is common for all users and which can load its session dependent stuff straight from the GraphQL API once it is displayed on the client device.

This approach will generally have higher performance and scale much better.

Should you really want to go the "SSR with user session data" route you start in the getServerSideProps(context) method, where context.req is the actual request which will have all your session data in it (cookies or headers).

This session data you can then extract from the req and pass on to the GraphQL server requests that require authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM