Skip to content

Commit 89b1280

Browse files
committed
refactor: reduce number of woo token generated
1 parent b9be40c commit 89b1280

File tree

3 files changed

+21
-7
lines changed

3 files changed

+21
-7
lines changed

src/graphql/clients/clientSideMakeClient.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,25 @@ import { createErrorLink } from '../utils';
88
import { PUBLIC_GATEWAY_URL } from '@/config/app';
99
import Cookies from 'js-cookie';
1010

11-
export const WOO_SESSION_KEY = 'woo-session';
11+
const WOO_SESSION_KEY = 'woo-session';
12+
13+
/**
14+
* Apollo Link to manage WooCommerce session tokens.
15+
* This link sets the session token in the request headers if available.
16+
*/
17+
export const wooSessionSetter = new ApolloLink((operation, forward) => {
18+
const token = Cookies.get(WOO_SESSION_KEY);
19+
if (token) {
20+
// Set session token in the request headers
21+
operation.setContext({
22+
headers: {
23+
'woocommerce-session': `Session ${token}`,
24+
},
25+
});
26+
}
27+
28+
return forward(operation);
29+
});
1230

1331
/**
1432
* Apollo Link to update the WooCommerce session token.
@@ -47,6 +65,7 @@ export const makeClient = () => {
4765
connectToDevTools: true,
4866
cache: new NextSSRInMemoryCache(),
4967
link: from([
68+
wooSessionSetter,
5069
wooSessionUpdater,
5170
createErrorLink(),
5271
new SSRMultipartLink({ stripDefer: true }),

src/graphql/clients/serverSideClient.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export const { getClient } = registerApolloClient(() => {
1010
uri: `${process.env.__NEXT_PRIVATE_ORIGIN}${PUBLIC_GATEWAY_URL}`,
1111
headers: {
1212
cookie: cookiesStore.toString(),
13+
'X-Server-Side': 'true',
1314
},
1415
});
1516

src/middleware.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import nextIntlMiddleware from 'next-intl/middleware';
44
import type { NextRequest } from 'next/server';
55
import { NextResponse } from 'next/server';
66
import { PUBLIC_GATEWAY_URL, protectedRoutes } from './config/app';
7-
import { WOO_SESSION_KEY } from './graphql/clients/clientSideMakeClient';
87

98
const intlMiddleware = (request: NextRequest) =>
109
Promise.resolve(
@@ -20,11 +19,6 @@ async function middleware(request: NextRequestWithAuth) {
2019
const { pathname } = request.nextUrl;
2120
request.headers.set('x-pathname', pathname);
2221

23-
const wooToken = request.cookies.get(WOO_SESSION_KEY)?.value;
24-
if (wooToken) {
25-
request.headers.set('woocommerce-session', `Session ${wooToken}`);
26-
}
27-
2822
if (pathname.startsWith(PUBLIC_GATEWAY_URL)) {
2923
request.headers.delete('cookie');
3024

0 commit comments

Comments
 (0)