Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@kampus/relay): attach ssr next-auth cookies to fetch req #631

Merged
merged 1 commit into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions apps/gql/app/graphql/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { type NextApiRequest, type NextApiResponse } from "next";
import { createSchema, createYoga } from "graphql-yoga";

import { getServerSession } from "@kampus/next-auth";
Expand All @@ -14,16 +13,14 @@ import { type KampusGQLContext } from "~/schema/types";
const typeDefs = readFileSync(join(process.cwd(), "schema/schema.graphql"), "utf8").toString();
const clients = createClients();

type ServerContext = { req: NextApiRequest; res: NextApiResponse } & KampusGQLContext;

const { handleRequest } = createYoga<ServerContext>({
schema: createSchema<ServerContext>({ typeDefs, resolvers }),
const { handleRequest } = createYoga<KampusGQLContext>({
schema: createSchema<KampusGQLContext>({ typeDefs, resolvers }),
logging: "debug",
graphiql: true,
context: async ({ req, res }) => {
context: async () => {
const loaders = createLoaders(clients);
const actions = createActions(clients);
const session = await getServerSession(req, res);
const session = await getServerSession();

return {
loaders,
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 19 additions & 4 deletions packages/relay/environment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { type ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
import {
Environment,
Network,
Expand All @@ -10,6 +11,8 @@ import {
type Variables,
} from "relay-runtime";

import { type Dictionary } from "@kampus/std";

const IS_SERVER = typeof window === typeof undefined;
const CACHE_TTL = 5 * 1000; // 5 seconds, to resolve preloaded results

Expand All @@ -19,12 +22,24 @@ export async function networkFetch(
request: RequestParameters,
variables: Variables
): Promise<GraphQLResponse> {
const headers: Dictionary<string> = {
Accept: "application/json",
"Content-Type": "application/json",
};

// pasaport wraps next-auth and uses its cookie auth mechanism to validate sessions.
// on browsers, fetch request automatically attaches the existing cookies
// but on next.js servers, `fetch` is pollyfilled, and does not pick up cookies
// we use `next/header`'s cookies() helper here
if (IS_SERVER) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nextHeaders = require("next/headers") as { cookies: () => ReadonlyRequestCookies };
headers.Cookie = nextHeaders.cookies().toString();
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @cansirin this should fix your problem for getting "null" sessions for server side requests.


const resp = await fetch(HTTP_ENDPOINT, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
headers,
body: JSON.stringify({
query: request.text,
variables,
Expand Down
1 change: 1 addition & 0 deletions packages/relay/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"extends": "../../package.json"
},
"dependencies": {
"@kampus/std": "*",
"react-relay": "15.0.0",
"relay-runtime": "15.0.0"
},
Expand Down
1 change: 1 addition & 0 deletions packages/std/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./assert-never";
export * from "./dictionary";