apps/web: pass token to GraphQL query (SSR)

This commit is contained in:
vchikalkin 2024-05-21 13:51:57 +03:00
parent 7d5be83e4c
commit 13cd93338f
6 changed files with 112 additions and 86 deletions

View File

@ -1,20 +1,20 @@
import { link } from './link';
import { createLink } from './link';
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { isServer } from 'tools/common';
/** @type {import('@apollo/client').ApolloClient<import('@apollo/client').NormalizedCacheObject>} */
let apolloClient;
function createApolloClient() {
function createApolloClient(headers) {
return new ApolloClient({
cache: new InMemoryCache(),
link,
link: createLink(headers),
ssrMode: isServer(),
});
}
export default function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient();
export default function initializeApollo(initialState, headers) {
const _apolloClient = apolloClient ?? createApolloClient(headers);
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here

View File

@ -2,6 +2,7 @@
import { message } from '@/Components/Common/Notification';
import { publicRuntimeConfigSchema } from '@/config/schema/runtime-config';
import getUrls from '@/config/urls';
import { getToken } from '@/utils/auth';
import { ApolloLink, from, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
@ -9,6 +10,7 @@ import { getCurrentScope } from '@sentry/nextjs';
import getConfig from 'next/config';
import { isServer } from 'tools';
export function createLink(headers) {
const { URL_CRM_GRAPHQL } = getUrls();
const modifyDataLink = new ApolloLink((operation, forward) => {
@ -78,6 +80,17 @@ const authLink = setContext((_, { headers: existingHeaders }) => {
};
}
if (isServer()) {
const token = getToken({ headers });
return {
headers: {
...existingHeaders,
authorization: `Bearer ${token}`,
},
};
}
return {
headers: {
...existingHeaders,
@ -107,4 +120,5 @@ const errorLink = onError(({ graphQLErrors, networkError, operation, response })
});
});
export const link = from([authLink, errorLink, modifyDataLink, httpLink]);
return from([authLink, errorLink, modifyDataLink, httpLink]);
}

View File

@ -29,7 +29,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, { cookie });
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

View File

@ -36,7 +36,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, { cookie });
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

View File

@ -37,7 +37,7 @@ export async function getServerSideProps({ req }) {
const { cookie = '' } = req.headers;
const queryClient = new QueryClient();
const apolloClient = initializeApollo();
const apolloClient = initializeApollo(null, { cookie });
const getUserType = makeGetUserType({ apolloClient, queryClient });
try {

12
apps/web/utils/auth.ts Normal file
View File

@ -0,0 +1,12 @@
import type { IncomingHttpHeaders } from 'http';
type Request = {
headers: IncomingHttpHeaders;
};
export function getToken({ headers }: Request) {
return headers.cookie
?.split(';')
.find((c) => c.trim().startsWith('token='))
?.split('=')[1];
}