Skip to content

Commit

Permalink
Add implementation of Next.js server cookies storage
Browse files Browse the repository at this point in the history
  • Loading branch information
typeofweb committed Nov 16, 2023
1 parent 30ff933 commit a8d23e3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@
"import": "./next/index.mjs",
"require": "./next/index.js"
},
"./next/server": {
"types": "./next/server.d.ts",
"import": "./next/server.mjs",
"require": "./next/server.js"
},
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
Expand Down
25 changes: 25 additions & 0 deletions src/next/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { StorageRepository } from "../types";
import { cookies } from "next/headers";

export const getNextServerCookiesStorage = (): StorageRepository => {
const cache = new Map<string, string>();
return {
getItem(key) {
// We need to cache the value because cookies() returns stale data
// if cookies().set(…) is called in the same request.
return cache.get(key) ?? cookies().get(key)?.value ?? null;
},
removeItem(key) {
cache.delete(key);
cookies().delete(key);
},
setItem(key, value) {
try {
cache.set(key, value);
cookies().set(key, value, { httpOnly: true, sameSite: "lax" });
} catch {
// noop
}
},
};
};

0 comments on commit a8d23e3

Please sign in to comment.