Skip to content

Commit b9be40c

Browse files
committed
refactor: store woo token in the cookie
1 parent 31ae05c commit b9be40c

File tree

4 files changed

+40
-59
lines changed

4 files changed

+40
-59
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"deepmerge": "^4.3.1",
2727
"graphql": "^16.8.1",
2828
"jotai": "^2.8.1",
29+
"js-cookie": "^3.0.5",
2930
"material-ui-confirm": "^3.0.7",
3031
"next": "14.2.20",
3132
"next-auth": "^4.24.10",
@@ -52,6 +53,7 @@
5253
"@graphql-typed-document-node/core": "^3.2.0",
5354
"@types/add": "^2",
5455
"@types/jest": "^29.5.12",
56+
"@types/js-cookie": "^3.0.6",
5557
"@types/node": "^20",
5658
"@types/react": "^18",
5759
"@types/react-dom": "^18",

src/graphql/clients/clientSideMakeClient.ts

Lines changed: 16 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -6,93 +6,50 @@ import {
66
} from '@apollo/experimental-nextjs-app-support/ssr';
77
import { createErrorLink } from '../utils';
88
import { PUBLIC_GATEWAY_URL } from '@/config/app';
9+
import Cookies from 'js-cookie';
910

10-
const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
11-
const WOO_SESSION_KEY = 'woo-session';
11+
export const WOO_SESSION_KEY = 'woo-session';
1212

1313
/**
14-
* Woo Session setter operation.
15-
* If we have a session token in localStorage, add it to the GraphQL request as a Session header.
16-
*/
17-
export const wooSessionSetter = new ApolloLink((operation, forward) => {
18-
/**
19-
* If session data exist in local storage, set value as session header.
20-
* Here we also delete the session if it is older than 7 days
21-
*/
22-
const localStorageValue = localStorage.getItem(WOO_SESSION_KEY);
23-
const sessionData = localStorageValue ? JSON.parse(localStorageValue) : null;
24-
25-
if (sessionData && sessionData.token && sessionData.createdTime) {
26-
const { token, createdTime } = sessionData;
27-
28-
// Check if the token is older than 7 days
29-
if (Date.now() - createdTime > SEVEN_DAYS) {
30-
// If it is, delete it
31-
localStorage.removeItem(WOO_SESSION_KEY);
32-
localStorage.setItem('woocommerce-cart', JSON.stringify({}));
33-
} else {
34-
// If it's not, use the token
35-
operation.setContext(() => ({
36-
headers: {
37-
'woocommerce-session': `Session ${token}`,
38-
},
39-
}));
40-
}
41-
}
42-
43-
return forward(operation);
44-
});
45-
46-
/**
47-
* Woo Session updater operation.
48-
*
49-
* This catches the incoming session token and stores it in localStorage, for future GraphQL requests.
14+
* Apollo Link to update the WooCommerce session token.
15+
* This link captures the session token from the response headers and stores it in cookies.
5016
*/
5117
export const wooSessionUpdater = new ApolloLink((operation, forward) =>
5218
forward(operation).map((response) => {
53-
/**
54-
* Check for session header and update session in local storage accordingly.
55-
*/
5619
const context = operation.getContext();
57-
const {
58-
response: { headers },
59-
} = context;
60-
61-
const session = headers.get('woocommerce-session');
20+
const session = context.response?.headers.get('woocommerce-session');
6221

6322
if (session) {
64-
if ('false' === session) {
65-
// Remove session data if session destroyed.
66-
localStorage.removeItem(WOO_SESSION_KEY);
67-
// Update session new data if changed.
68-
} else if (!localStorage.getItem(WOO_SESSION_KEY)) {
69-
localStorage.setItem(
70-
WOO_SESSION_KEY,
71-
JSON.stringify({ token: session, createdTime: Date.now() }),
72-
);
23+
if (session === 'false') {
24+
// Remove session data if the session is destroyed
25+
Cookies.remove(WOO_SESSION_KEY);
26+
} else if (!Cookies.get(WOO_SESSION_KEY)) {
27+
// Store new session token if it doesn't exist
28+
Cookies.set(WOO_SESSION_KEY, session, { expires: 7 });
7329
}
7430
}
7531

7632
return response;
7733
}),
7834
);
7935

36+
// Create an HTTP link for Apollo Client
8037
const httpLink = new HttpLink({
8138
uri: PUBLIC_GATEWAY_URL,
8239
});
8340

41+
/**
42+
* Function to create an Apollo Client instance with SSR support.
43+
*/
8444
export const makeClient = () => {
8545
return new NextSSRApolloClient({
8646
ssrMode: true,
8747
connectToDevTools: true,
8848
cache: new NextSSRInMemoryCache(),
8949
link: from([
90-
wooSessionSetter,
9150
wooSessionUpdater,
9251
createErrorLink(),
93-
new SSRMultipartLink({
94-
stripDefer: true,
95-
}),
52+
new SSRMultipartLink({ stripDefer: true }),
9653
httpLink,
9754
]),
9855
});

src/middleware.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ 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';
78

89
const intlMiddleware = (request: NextRequest) =>
910
Promise.resolve(
@@ -19,6 +20,11 @@ async function middleware(request: NextRequestWithAuth) {
1920
const { pathname } = request.nextUrl;
2021
request.headers.set('x-pathname', pathname);
2122

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

yarn.lock

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3101,6 +3101,13 @@ __metadata:
31013101
languageName: node
31023102
linkType: hard
31033103

3104+
"@types/js-cookie@npm:^3.0.6":
3105+
version: 3.0.6
3106+
resolution: "@types/js-cookie@npm:3.0.6"
3107+
checksum: 10c0/173afaf5ea9d86c22395b9d2a00b6adb0006dcfef165d6dcb0395cdc32f5a5dcf9c3c60f97194119963a15849b8f85121e1ae730b03e40bc0c29b84396ba22f9
3108+
languageName: node
3109+
linkType: hard
3110+
31043111
"@types/js-yaml@npm:^4.0.0":
31053112
version: 4.0.9
31063113
resolution: "@types/js-yaml@npm:4.0.9"
@@ -7603,6 +7610,13 @@ __metadata:
76037610
languageName: node
76047611
linkType: hard
76057612

7613+
"js-cookie@npm:^3.0.5":
7614+
version: 3.0.5
7615+
resolution: "js-cookie@npm:3.0.5"
7616+
checksum: 10c0/04a0e560407b4489daac3a63e231d35f4e86f78bff9d792011391b49c59f721b513411cd75714c418049c8dc9750b20fcddad1ca5a2ca616c3aca4874cce5b3a
7617+
languageName: node
7618+
linkType: hard
7619+
76067620
"js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0":
76077621
version: 4.0.0
76087622
resolution: "js-tokens@npm:4.0.0"
@@ -8515,6 +8529,7 @@ __metadata:
85158529
"@persian-tools/persian-tools": "npm:^3.5.2"
85168530
"@types/add": "npm:^2"
85178531
"@types/jest": "npm:^29.5.12"
8532+
"@types/js-cookie": "npm:^3.0.6"
85188533
"@types/node": "npm:^20"
85198534
"@types/react": "npm:^18"
85208535
"@types/react-dom": "npm:^18"
@@ -8534,6 +8549,7 @@ __metadata:
85348549
husky: "npm:^9.0.11"
85358550
jest: "npm:^29.7.0"
85368551
jotai: "npm:^2.8.1"
8552+
js-cookie: "npm:^3.0.5"
85378553
material-ui-confirm: "npm:^3.0.7"
85388554
next: "npm:14.2.20"
85398555
next-auth: "npm:^4.24.10"

0 commit comments

Comments
 (0)