Skip to content

Commit

Permalink
Added SameSite option for cookie storage
Browse files Browse the repository at this point in the history
Firefox warns about not setting this option.
It is now set to Strict by default.
  • Loading branch information
felixgirault committed Feb 21, 2025
1 parent 49bbaeb commit f60eed7
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,11 @@ var orejimeConfig = {
// You can provide a custom domain for the Orejime cookie, for example to make it available on every associated subdomains.
domain: 'mydomain.com',

// [optional]
// Whether the cookie should be shared via cross-site requests.
// @see https://web.dev/articles/samesite-cookies-explained
sameSite: 'strict',

// [optional]
// You can provide a custom function to serialize the cookie contents.
stringify: (contents) => JSON.stringify(contents),
Expand Down
5 changes: 3 additions & 2 deletions src/core/CookieConsentsRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default class CookieConsentsRepository implements ConsentsRepository {
name: 'eu-consent',
domain: undefined,
duration: 120,
sameSite: 'strict',
parse: JSON.parse,
stringify: JSON.stringify,
...options
Expand All @@ -23,8 +24,8 @@ export default class CookieConsentsRepository implements ConsentsRepository {
}

write(consents: ConsentsMap) {
const {name, domain, duration, stringify} = this.#options;
setCookie(name, stringify(consents), duration, domain);
const {name, domain, duration, sameSite, stringify} = this.#options;
setCookie(name, stringify(consents), duration, domain, sameSite);
}

clear() {
Expand Down
3 changes: 3 additions & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {CookieSameSite} from './utils/cookies';

export type PurposeCookieProps = [
pattern: RegExp,
path: string,
Expand All @@ -21,6 +23,7 @@ export type CookieOptions = {
name: string;
domain?: string;
duration: number;
sameSite?: CookieSameSite;
parse: (consents: string) => ConsentsMap;
stringify: (consents: ConsentsMap) => string;
};
8 changes: 6 additions & 2 deletions src/core/utils/cookies.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import Cookie from 'js-cookie';

export type CookieSameSite = 'strict' | 'lax' | 'none';

export const getCookieNames = () =>
document.cookie.split(';').reduce((names, cookie) => {
const [name] = cookie.split('=', 2);
Expand All @@ -12,11 +14,13 @@ export const setCookie = (
name: string,
value = '',
days = 0,
domain?: string
domain?: string,
sameSite?: CookieSameSite
) => {
Cookie.set(name, value, {
expires: days,
domain
domain,
sameSite
});
};

Expand Down

0 comments on commit f60eed7

Please sign in to comment.