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,9 +10,10 @@ import { getCurrentScope } from '@sentry/nextjs';
import getConfig from 'next/config';
import { isServer } from 'tools';
const { URL_CRM_GRAPHQL } = getUrls();
export function createLink(headers) {
const { URL_CRM_GRAPHQL } = getUrls();
const modifyDataLink = new ApolloLink((operation, forward) => {
const modifyDataLink = new ApolloLink((operation, forward) => {
const context = operation?.getContext();
return forward(operation).map((response) => {
@ -58,13 +60,13 @@ const modifyDataLink = new ApolloLink((operation, forward) => {
return response;
});
});
});
const httpLink = new HttpLink({
const httpLink = new HttpLink({
uri: URL_CRM_GRAPHQL,
});
});
const authLink = setContext((_, { headers: existingHeaders }) => {
const authLink = setContext((_, { headers: existingHeaders }) => {
if (process.env.NODE_ENV === 'development') {
const { publicRuntimeConfig } = getConfig();
const { DEV_AUTH_TOKEN } = publicRuntimeConfigSchema.parse(publicRuntimeConfig);
@ -78,16 +80,27 @@ const authLink = setContext((_, { headers: existingHeaders }) => {
};
}
if (isServer()) {
const token = getToken({ headers });
return {
headers: {
...existingHeaders,
authorization: `Bearer ${token}`,
},
};
}
return {
headers: {
...existingHeaders,
},
};
});
});
const key = 'APOLLO_GRAPHQL';
const key = 'APOLLO_GRAPHQL';
const errorLink = onError(({ graphQLErrors, networkError, operation, response }) => {
const errorLink = onError(({ graphQLErrors, networkError, operation, response }) => {
const scope = getCurrentScope();
scope.setTag('operationName', operation.operationName);
@ -105,6 +118,7 @@ const errorLink = onError(({ graphQLErrors, networkError, operation, response })
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];
}