Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ This plugin is inspired by [connect-flash](https://github.com/jaredhanson/connec
npm i @fastify/flash
```

TypeScript note: when using modern Fastify typings, `request.flash()` and
`reply.flash()` are inferred from the registered instance. Legacy global
augmentation remains available for compatibility.

## Usage

Flash messages are stored in the session. First, we need to register the session plugin: [@fastify/secure-session](https://www.npmjs.com/package/@fastify/secure-session).
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"devDependencies": {
"@fastify/secure-session": "^8.0.0",
"@types/node": "^25.0.3",
"fastify": "^5.0.0",
"fastify": "github:fastify/fastify#feat/typed-decorators",
"prettier": "^3.2.5",
"rimraf": "^6.0.1",
"borp": "^0.21.0",
Expand All @@ -73,7 +73,7 @@
"typescript": "~5.9.2"
},
"dependencies": {
"fastify-plugin": "^5.0.0"
"fastify-plugin": "github:fastify/fastify-plugin#feat/create-plugin"
},
"files": [
"/lib",
Expand Down
68 changes: 44 additions & 24 deletions src/flash.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
import { format } from 'node:util'

type ReplyReturn =
| {
[k: string]: string[] | undefined
type FlashStore = Record<string, string[] | undefined>

type ReplyReturn = FlashStore | string[]

interface SessionLike {
get (key: string): unknown
set (key: string, value: unknown): void
}

interface FlashRequestContext {
session?: SessionLike
}

interface FlashReplyContext {
request: FlashRequestContext
}

const isObject = (value: unknown): value is Record<string, unknown> => {
return typeof value === 'object' && value !== null
}

const getFlashStore = (value: unknown): FlashStore => {
if (!isObject(value)) {
return {}
}
| string[]

return value as FlashStore
}

export function flashFactory () {
return {
request (type: string, ...message: string[] | [string[]]): number {
request (this: FlashRequestContext, type: string, ...message: string[] | [string[]]): number {
if (!this.session) {
throw new Error('Session not found')
}
let currentSession = this.session.get('flash')
if (!currentSession) {
currentSession = {}
this.session.set('flash', currentSession)
}

const session = this.session
let currentSession = getFlashStore(session.get('flash'))

if (message.length === 0) {
throw new Error('Provide a message to flash.')
Expand All @@ -26,42 +47,41 @@ export function flashFactory () {
for (let i = 0; i < message[0].length; i++) {
currentSession = {
...currentSession,
[type]: (currentSession[type] || []).concat(message[0][i]),
[type]: (currentSession[type] ?? []).concat(message[0][i]),
}
}
} else {
currentSession = {
...currentSession,
[type]: (currentSession[type] || []).concat(
[type]: (currentSession[type] ?? []).concat(
message.length > 1 ? format.apply(undefined, message) : message[0]
),
}
}
this.session.set('flash', currentSession)
return this.session.get('flash')[type].length

session.set('flash', currentSession)
return currentSession[type]?.length ?? 0
},

reply (type?: string): ReplyReturn {
reply (this: FlashReplyContext, type?: string): ReplyReturn {
if (!this.request.session) {
throw new Error('Session not found')
}

const session = this.request.session
if (!type) {
const allMessages = this.request.session.get('flash')
this.request.session.set('flash', {})
const allMessages = getFlashStore(session.get('flash'))
session.set('flash', {})
return allMessages
}

let data = this.request.session.get('flash')
if (!data) {
data = {}
}

const data = getFlashStore(session.get('flash'))
const messages = data[type]
delete data[type]

this.request.session.set('flash', data)
session.set('flash', data)

return messages || []
return messages ?? []
},
}
}
37 changes: 31 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,45 @@
import type {
AnyFastifyInstance,
ApplyDecorators,
FastifyPluginCallback,
UnEncapsulatedPlugin
} from 'fastify'
import fp from 'fastify-plugin'
import { flashFactory } from './flash'

declare module 'fastify' {
export interface FastifyRequest {
declare namespace fastifyFlash {
export interface FastifyFlashRequestDecorators {
flash: ReturnType<typeof flashFactory>['request']
}
export interface FastifyReply {

export interface FastifyFlashReplyDecorators {
flash: ReturnType<typeof flashFactory>['reply']
}

export type FastifyFlashPluginDecorators = {
request: FastifyFlashRequestDecorators
reply: FastifyFlashReplyDecorators
}

export type FastifyFlashPlugin<TInstance extends AnyFastifyInstance = AnyFastifyInstance> = UnEncapsulatedPlugin<
FastifyPluginCallback<
{},
TInstance,
ApplyDecorators<TInstance, FastifyFlashPluginDecorators>
>
>
}

export = fp<{}>(
const fastifyFlashPlugin: fastifyFlash.FastifyFlashPlugin = fp(
function (fastify, _opts, done) {
const flash = flashFactory()

fastify.decorateRequest('flash', flash.request)
fastify.decorateReply('flash', flash.reply)
const decorated = fastify
.decorateRequest('flash', flash.request)
.decorateReply('flash', flash.reply)

done()
return decorated
},
{
fastify: '5.x',
Expand All @@ -26,3 +49,5 @@ export = fp<{}>(
},
}
)

export = fastifyFlashPlugin
Loading
Loading