Skip to content

Commit

Permalink
The redirect function now accept the cookies object.
Browse files Browse the repository at this point in the history
  • Loading branch information
ciscoheat committed Dec 15, 2023
1 parent 9cb18e1 commit ea1bea1
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 27 deletions.
8 changes: 6 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ Headlines: Added, Changed, Deprecated, Removed, Fixed, Security
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.2.3] - 2023-12-15
## [2.3.0] - 2023-12-15

### Added

- The `redirect` function can now take the [cookies](https://kit.svelte.dev/docs/load#cookies) object as well as the whole RequestEvent.

### Fixed

- Added peer dependency support for SvelteKit 2. ([#32](https://github.com/ciscoheat/sveltekit-flash-message/issues/32))
- Peer dependency support for SvelteKit 2. ([#32](https://github.com/ciscoheat/sveltekit-flash-message/issues/32))

## [2.2.2] - 2023-11-13

Expand Down
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,20 @@ throw redirect(
status: number,
location: string,
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
)

// Makes a 303 redirect
throw redirect(
location: string,
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
)

// Makes a 303 redirect to the current URL
throw redirect(
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
)

// For compatibility, the sveltekit signature can also be used,
Expand All @@ -120,15 +120,15 @@ throw redirect(
import { redirect } from 'sveltekit-flash-message/server';

export const actions = {
default: async (event) => {
const form = await event.request.formData();
default: async ({ request, locals, cookies }) => {
const form = await request.formData();

await api('POST', `/todos/${event.locals.userid}`, {
await api('POST', `/todos/${locals.userid}`, {
text: form.get('text')
});

const message = { type: 'success', message: "That's the entrepreneur spirit!" } as const;
throw redirect(message, event);
throw redirect(message, cookies);
}
};
```
Expand All @@ -141,9 +141,9 @@ export const actions = {
import type { RequestEvent } from '@sveltejs/kit';
import { redirect } from 'sveltekit-flash-message/server';

export const POST = async (event) => {
export const POST = async ({ cookies }) => {
const message = { type: 'success', message: 'Endpoint POST successful!' } as const;
throw redirect(303, '/', message, event);
throw redirect(303, '/', message, cookies);
};
```

Expand Down
32 changes: 20 additions & 12 deletions src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { CookieSerializeOptions } from './cookie-es-main/index.js';
// Cannot change.
const cookieName = 'flash';

export const flashCookieOptions: CookieSerializeOptions & { path: string } = {
export const flashCookieOptions: CookieSerializeOptions = {
path: '/',
maxAge: 120,
httpOnly: false,
Expand Down Expand Up @@ -62,7 +62,7 @@ export function _loadFlash<T extends ServerLoadEvent>(
//d('Possible fetch request, keeping cookie for client.');
} else {
//d('Flash cookie found, clearing');
event.cookies.delete(cookieName, { path: flashCookieOptions.path });
event.cookies.delete(cookieName, { path: flashCookieOptions.path ?? '/' });
}

try {
Expand Down Expand Up @@ -98,11 +98,11 @@ export function redirect(status: RedirectStatus, location: string | URL): Return
* If thrown during request handling, SvelteKit will return a redirect response.
* Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
* @param {App.PageData['flash']} message The flash message.
* @param {RequestEvent} event The event for the load function or form action.
* @param {RequestEvent | Cookies} event The event for the load function or form action.
*/
export function redirect(
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
): ReturnType<typeof redir>;

/**
Expand All @@ -111,12 +111,12 @@ export function redirect(
* Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
* @param {string | URL} location The redirect URL/location.
* @param {App.PageData['flash']} message The flash message.
* @param {RequestEvent} event The event for the load function or form action.
* @param {RequestEvent | Cookies} event The event for the load function or form action.
*/
export function redirect(
location: string | URL,
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
): ReturnType<typeof redir>;

/**
Expand All @@ -126,20 +126,20 @@ export function redirect(
* @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308.
* @param {string | URL} location The redirect URL/location.
* @param {App.PageData['flash']} message The flash message.
* @param {RequestEvent} event The event for the load function or form action.
* @param {RequestEvent | Cookies} event The event for the load function or form action.
*/
export function redirect(
status: RedirectStatus,
location: string | URL,
message: App.PageData['flash'],
event: RequestEvent
event: RequestEvent | Cookies
): ReturnType<typeof redir>;

export function redirect(
status: unknown,
location: unknown,
message?: unknown,
event?: RequestEvent
event?: RequestEvent | Cookies
): ReturnType<typeof redir> {
switch (arguments.length) {
case 2:
Expand Down Expand Up @@ -184,12 +184,17 @@ function realRedirect(
status: RedirectStatus,
location: string | URL,
message?: App.PageData['flash'],
event?: RequestEvent
event?: RequestEvent | Cookies
) {
if (!message) return redir(status, location.toString());
if (!event) throw new Error('RequestEvent is required for redirecting with flash message');

event.cookies.set(cookieName, JSON.stringify(message), flashCookieOptions);
const cookies = 'cookies' in event ? event.cookies : event;

cookies.set(cookieName, JSON.stringify(message), {
...flashCookieOptions,
path: flashCookieOptions.path ?? '/'
});
return redir(status, location.toString());
}

Expand All @@ -202,5 +207,8 @@ function realRedirect(
*/
export function setFlash(message: App.PageData['flash'], event: RequestEvent | Cookies) {
const cookies = 'cookies' in event ? event.cookies : event;
cookies.set(cookieName, JSON.stringify(message), flashCookieOptions);
cookies.set(cookieName, JSON.stringify(message), {
...flashCookieOptions,
path: flashCookieOptions.path ?? '/'
});
}
6 changes: 3 additions & 3 deletions src/routes/(app)/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const actions = {
);
},

enhanced: async (event) => {
enhanced: async ({ cookies }) => {
throw redirect(
'/posted',
[
Expand All @@ -32,7 +32,7 @@ export const actions = {
text: '+page.server.ts POST to /posted ' + count.next()
}
],
event
cookies
);
},

Expand All @@ -45,7 +45,7 @@ export const actions = {
},

async toast(event) {
throw redirect(
redirect(
[
{
status: 'ok',
Expand Down
3 changes: 2 additions & 1 deletion src/routes/(app)/issue-11/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export const load = async (event) => {
text: 'Redirecting back to start.'
} as const;
console.log('🚀 ~ /issue-11 ~ message:', message);
throw redirect(303, '/', [message], event);
// SvelteKit 2 check (no throw)
redirect(303, '/', [message], event);
};

/*
Expand Down

0 comments on commit ea1bea1

Please sign in to comment.