Skip to content

Commit 8de6ee9

Browse files
committed
fix: Execute afterLogout hooks at logout endpoint (#16)
1 parent 5e9b181 commit 8de6ee9

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

packages/dev/src/payload/collections/users.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,13 @@ const Users: CollectionConfig = {
158158
],
159159
},
160160
],
161+
/* hooks: {
162+
afterLogout: [
163+
({ req }) => {
164+
console.log("User logged out", req.user?.id);
165+
},
166+
],
167+
}, */
161168
};
162169

163170
export default Users;

packages/payload-authjs/src/payload/collection/endpoints/logout.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";
33
import type { Endpoint } from "payload";
44
import { withPayload } from "../../../authjs/withPayload";
55
import type { AuthjsPluginConfig } from "../../plugin";
6+
import { getRequestCollection } from "../../utils/getRequestCollection";
67

78
/**
89
* Override the default logout endpoint to destroy the authjs session
@@ -31,6 +32,18 @@ export const logoutEndpoint: (pluginOptions: AuthjsPluginConfig) => Endpoint = p
3132
response.cookies.set(cookie.name, cookie.value, cookie.options);
3233
}
3334

35+
// Execute afterLogout hooks
36+
const { config: collection } = getRequestCollection(req);
37+
if (collection.hooks?.afterLogout?.length) {
38+
for (const hook of collection.hooks.afterLogout) {
39+
await hook({
40+
collection,
41+
context: req.context,
42+
req,
43+
});
44+
}
45+
}
46+
3447
return response;
3548
},
3649
});
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { APIError, type Collection, type PayloadRequest } from "payload";
2+
3+
/**
4+
* Get the collection from the request
5+
*
6+
* @see https://github.com/payloadcms/payload/blob/main/packages/payload/src/utilities/getRequestEntity.ts#L8
7+
*/
8+
export const getRequestCollection = (req: PayloadRequest): Collection => {
9+
const collectionSlug = req.routeParams?.collection;
10+
11+
if (typeof collectionSlug !== "string") {
12+
throw new APIError(`No collection was specified`, 400);
13+
}
14+
15+
const collection = req.payload.collections[collectionSlug];
16+
17+
if (!collection) {
18+
throw new APIError(`Collection with the slug ${collectionSlug} was not found`, 404);
19+
}
20+
21+
return collection;
22+
};

0 commit comments

Comments
 (0)