Skip to content

Commit

Permalink
adding global cookie override
Browse files Browse the repository at this point in the history
  • Loading branch information
AlemTuzlak committed Feb 18, 2024
1 parent 005c1c0 commit 4f59826
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ export default function App() {

![react-toastify](./assets/sonner.gif)

## Overriding cookie options

You can override the default cookie options by passing in your own options via the `setToastCookieOptions` function.

```tsx
import { setToastCookieOptions } from "remix-toast";

setToastCookieOptions({
secrets:
process.env.NODE_ENV === "production"
? [process.env.SESSION_SECRET]
: ["secret"]
});
```

## Creating utility functions with custom sessions

`createToastUtilsWithCustomSession` is a function that allows you to create a custom session for your toasts. This is useful if you want to have different types of toasts for different parts of your app.
Expand Down
35 changes: 27 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,42 @@ import {
redirect,
json,
SessionStorage,
SessionIdStorageStrategy,
} from "@remix-run/server-runtime";
import { FlashSessionValues, ToastMessage, flashSessionValuesSchema } from "./schema";
import { sign, unsign } from "./crypto";

const FLASH_SESSION = "flash";
const createCookie = createCookieFactory({ sign, unsign });
type ToastCookieOptions = Partial<SessionIdStorageStrategy["cookie"]>;

const toastCookieOptions = {
name: "toast-session",
sameSite: "lax",
path: "/",
httpOnly: true,
secrets: ["s3Cr3t"],
} satisfies ToastCookieOptions;

const sessionStorage = createCookieSessionStorageFactory(createCookie)({
cookie: {
name: "toast-session",
sameSite: "lax",
path: "/",
httpOnly: true,
secrets: ["s3Cr3t"],
},
cookie: toastCookieOptions,
});

/**
* Sets the cookie options to be used for the toast cookie
*
* @param options Cookie options to be used for the toast cookie
*/
export function setToastCookieOptions(options: ToastCookieOptions) {
Object.assign(toastCookieOptions, options);
Object.assign(
sessionStorage,
createCookieSessionStorageFactory(createCookie)({
cookie: toastCookieOptions,
}),
);
}

function getSessionFromRequest(request: Request, customSession?: SessionStorage) {
const cookie = request.headers.get("Cookie");
const sessionToUse = customSession ? customSession : sessionStorage;
Expand Down Expand Up @@ -113,7 +132,7 @@ export async function getToast(
return { toast, headers };
}

export type { ToastMessage };
export type { ToastMessage, ToastCookieOptions };

/**
* Helper method used to initialize the whole library using a custom session. Returns all the utilities enhanced with the custom session
Expand Down

0 comments on commit 4f59826

Please sign in to comment.