### Install @fastify/flash Source: https://github.com/fastify/fastify-flash/blob/main/README.md Install the @fastify/flash package using npm. ```bash npm i @fastify/flash ``` -------------------------------- ### TypeScript Support Example Source: https://context7.com/fastify/fastify-flash/llms.txt Shows how @fastify/flash integrates with TypeScript, providing type safety for `req.flash` and `reply.flash` decorators. ```typescript import Fastify, { FastifyRequest, FastifyReply } from 'fastify' import fastifyFlash from '@fastify/flash' const fastify = Fastify() fastify.register(fastifyFlash) fastify.get('/typed', (req: FastifyRequest, reply: FastifyReply) => { // TypeScript knows req.flash returns number const count: number = req.flash('info', 'Typed message') // TypeScript knows reply.flash returns string[] or Record const messages = reply.flash('info') as string[] reply.send({ count, messages }) }) ``` -------------------------------- ### Multiple Flash Types Example Source: https://context7.com/fastify/fastify-flash/llms.txt Shows how different flash message types are stored and consumed independently. Consuming one type does not affect others. ```typescript fastify.get('/notify', (req, reply) => { req.flash('info', 'Welcome back') req.flash('notice', 'Last login was yesterday') // Read only "info" — "notice" remains in session untouched const info = reply.flash('info') as string[] // info === ["Welcome back"] // "notice" is still available for the next read const notice = reply.flash('notice') as string[] // notice === ["Last login was yesterday"] reply.send({ info, notice }) // { "info": ["Welcome back"], "notice": ["Last login was yesterday"] } }) ``` -------------------------------- ### Cross-Request Flash Passing Example Source: https://context7.com/fastify/fastify-flash/llms.txt Demonstrates setting flash messages in one request, redirecting, and then reading them in the next request. Flash data survives the redirect and is cleared on read. ```typescript import Fastify from 'fastify' import fastifySession from '@fastify/secure-session' import fastifyFlash from '@fastify/flash' import { readFileSync } from 'node:fs' const fastify = Fastify() fastify.register(fastifySession, { key: readFileSync('secret-key') }) fastify.register(fastifyFlash) // Step 1: Validate form and set flash, then redirect fastify.post('/submit', (req, reply) => { const body = req.body as { username?: string; password?: string } if (!body.username || !body.password) { req.flash('warning', ['Username is required', 'Password is required']) return reply.redirect('/form') // flash survives this redirect } req.flash('success', 'Logged in successfully') reply.redirect('/dashboard') }) // Step 2: Render the form — flash messages consumed here and cleared fastify.get('/form', (_, reply) => { const warnings = reply.flash('warning') as string[] // On second visit warnings === [] (already consumed) reply.send({ warnings }) // First visit: { warnings: ["Username is required", "Password is required"] } // Second visit: { warnings: [] } }) fastify.get('/dashboard', (_, reply) => { const success = reply.flash('success') as string[] reply.send({ success }) // { success: ["Logged in successfully"] } }) ``` -------------------------------- ### Read and Clear Flash Messages with reply.flash Source: https://context7.com/fastify/fastify-flash/llms.txt Use `reply.flash` to read messages from the session and clear them atomically. Call with a type to get messages of that type, or with no arguments to get all messages and clear the entire store. ```typescript fastify.get('/dashboard', (req, reply) => { // Read a specific type — clears only "error" messages const errors = reply.flash('error') as string[] // errors === ["Invalid credentials"] or [] // Read a different type independently const warnings = reply.flash('warning') as string[] // warnings === ["Username is required", "Password is required"] or [] // Read ALL types at once and clear everything // Returns: { error: string[], warning: string[], info: string[], ... } const allMessages = reply.flash() as Record // allMessages === { // notice: ["Last login: yesterday", "New feature available"], // info: ["Hello Alice, you have 3 new messages"] // } // Accessing a type that was never set returns an empty array (no error) const missing = reply.flash('nonexistent') as string[] // missing === [] reply.send({ errors, warnings, allMessages }) }) ``` -------------------------------- ### Set and Get Flash Messages Source: https://github.com/fastify/fastify-flash/blob/main/README.md Use req.flash to set messages and reply.flash to retrieve them. Messages can be set with a type and a single string, an array of strings, or formatted using util.format. Retrieving all messages returns an object, while retrieving by type returns an array. ```javascript fastify.get('/test', (req, reply) => { req.flash('warning', ['username required', 'password required']) const warning = reply.flash('warning') reply.send({ warning }) // {"warning":["username required","password required"]} }) ``` -------------------------------- ### Get Flash Messages by Type Source: https://github.com/fastify/fastify-flash/blob/main/README.md Retrieve flash messages of a specific type as an array. ```javascript reply.flash('info') // returns an array of messages that are stored with the provided type ``` -------------------------------- ### Get All Flash Messages Source: https://github.com/fastify/fastify-flash/blob/main/README.md Retrieve all flash messages stored in the session as an object. ```javascript reply.flash() // returns all messages as object { [k: string]: undefined | string[] } ``` -------------------------------- ### Get Flash Messages Source: https://github.com/fastify/fastify-flash/blob/main/README.md Retrieves flash messages. You can get all messages stored in the session or messages of a specific type. ```APIDOC ## Get Flash Messages ### Description Retrieves flash messages stored in the session. Can fetch all messages or messages of a specific type. ### Method Signature ```typescript reply.flash(type?: string): { [k: string]: undefined | string[] } | string[] ``` ### Usage Examples - `reply.flash() // returns all messages as an object { [k: string]: undefined | string[] }` - `reply.flash('info') // returns an array of messages stored with the type 'info'` ### Returns - `{ [k: string]: undefined | string[] } | string[]`: An object containing all flash messages or an array of messages for a specific type. ``` -------------------------------- ### Register Fastify Session and Flash Plugins Source: https://github.com/fastify/fastify-flash/blob/main/README.md Register the @fastify/secure-session and @fastify/flash plugins with Fastify. Ensure the session plugin is configured with a secret key and cookie path. The flash plugin can be configured with a prefix. ```javascript const fastify = require('fastify')() const fastifySession = require('@fastify/secure-session') const fastifyFlash = require('@fastify/flash') fastify.register(fastifySession, { // adapt this to point to the directory where secret-key is located key: fs.readFileSync(path.join(__dirname, 'secret-key')), cookie: { // options from setCookie, see https://github.com/fastify/fastify-cookie path: "/" } }) fastify.register(fastifyFlash, { prefix: "/" }) ``` -------------------------------- ### Register @fastify/flash Plugin Source: https://context7.com/fastify/fastify-flash/llms.txt Register the @fastify/flash plugin after a session plugin like @fastify/secure-session. Ensure `req.session` is available before registering flash. ```typescript import Fastify from 'fastify' import fastifySession from '@fastify/secure-session' import fastifyFlash from '@fastify/flash' import { readFileSync } from 'node:fs' import { join } from 'node:path' const fastify = Fastify() // Session plugin must be registered first fastify.register(fastifySession, { key: readFileSync(join(__dirname, 'secret-key')), // 32-byte key file cookie: { path: '/' }, }) // Then register flash fastify.register(fastifyFlash) fastify.listen({ port: 3000 }) ``` -------------------------------- ### Error Handling: Session Not Configured Source: https://context7.com/fastify/fastify-flash/llms.txt Illustrates that calling `req.flash` without a session plugin registered throws a 500 Internal Server Error with a 'Session not found' message. ```typescript // Without a session plugin registered: fastify.get('/no-session', async (req) => { req.flash('error', 'This will throw') // Response: { "statusCode": 500, "error": "Internal Server Error", "message": "Session not found" } }) ``` -------------------------------- ### Set Flash Message (Formatted String) Source: https://github.com/fastify/fastify-flash/blob/main/README.md Set a flash message using util.format for string formatting. ```javascript req.flash('info', 'Hello %s', 'Jared') // will use util.format to format the string ``` -------------------------------- ### Error Handling: Missing Message Argument Source: https://context7.com/fastify/fastify-flash/llms.txt Demonstrates that calling `req.flash` without a message argument throws a 500 Internal Server Error. ```typescript fastify.get('/bad-set', (req) => { // ERROR: no message provided req.flash('info') // Response: { "statusCode": 500, "error": "Internal Server Error", "message": "Provide a message to flash." } }) ``` -------------------------------- ### Set Flash Messages with req.flash Source: https://context7.com/fastify/fastify-flash/llms.txt Use `req.flash` to store one or more messages under a type key in the session. Messages accumulate with repeated calls for the same type. Supports single strings, arrays, and formatted strings. ```typescript fastify.get('/login-error', (req, reply) => { // Single string message const count1 = req.flash('error', 'Invalid credentials') // count1 === 1 // Multiple messages in one call using an array const count2 = req.flash('warning', ['Username is required', 'Password is required']) // count2 === 2 // util.format-style interpolation req.flash('info', 'Hello %s, you have %d new messages', 'Alice', 3) // stored as: "Hello Alice, you have 3 new messages" // Accumulating multiple calls of the same type req.flash('notice', 'Last login: yesterday') req.flash('notice', 'New feature available') // session now has notice: ["Last login: yesterday", "New feature available"] reply.redirect('/dashboard') }) ``` -------------------------------- ### Set Flash Message (Array of Strings) Source: https://github.com/fastify/fastify-flash/blob/main/README.md Set multiple flash messages of a specific type using an array. ```javascript req.flash('warning', ['username required', 'password required']) ``` -------------------------------- ### Set Flash Message (Single String) Source: https://github.com/fastify/fastify-flash/blob/main/README.md Set a single flash message of a specific type. ```javascript req.flash('info', 'Welcome back') ``` -------------------------------- ### Set Flash Messages Source: https://github.com/fastify/fastify-flash/blob/main/README.md Allows you to set flash messages of a specific type. Messages can be single strings or arrays of strings. The function returns the number of messages stored. ```APIDOC ## Set Flash Messages ### Description Sets flash messages of a specified type. Supports single messages, arrays of messages, and formatted strings using `util.format`. ### Method Signature ```typescript req.flash(type: string, ...message: string[] | [string[]]): number ``` ### Usage Examples - `req.flash('info', 'Welcome back')` - `req.flash('warning', ['username required', 'password required']) - `req.flash('info', 'Hello %s', 'Jared') // uses util.format` ### Returns - `number`: The number of messages stored for the given type. ``` -------------------------------- ### reply.flash(type?) — Read and Clear Flash Messages Source: https://context7.com/fastify/fastify-flash/llms.txt Reads flash messages from the session and removes them atomically so they are shown exactly once. Can read a specific type or all types. ```APIDOC ## reply.flash(type?) — Read and Clear Flash Messages ### Description Reads flash messages from the session and removes them atomically so they are shown exactly once. When called with a `type` string, returns `string[]` for that type (empty array if none exist). When called with no argument, returns all messages as `{ [type]: string[] }` and clears the entire flash store. ### Method Signature `reply.flash(type?: string): string[] | Record` ### Parameters - **type** (string) - Optional - The type key of the flash messages to retrieve. If omitted, all flash messages are retrieved. ### Returns - (string[]) - If a `type` is provided, an array of strings representing the flash messages of that type. Returns an empty array if no messages of that type exist. - (Record) - If no `type` is provided, an object where keys are message types and values are arrays of strings representing the flash messages for each type. This also clears all flash messages from the session. ### Examples ```typescript // Read a specific type — clears only "error" messages const errors = reply.flash('error') as string[] // errors === ["Invalid credentials"] or [] // Read a different type independently const warnings = reply.flash('warning') as string[] // warnings === ["Username is required", "Password is required"] or [] // Read ALL types at once and clear everything // Returns: { error: string[], warning: string[], info: string[], ... } const allMessages = reply.flash() as Record // allMessages === { // notice: ["Last login: yesterday", "New feature available"], // info: ["Hello Alice, you have 3 new messages"] // } // Accessing a type that was never set returns an empty array (no error) const missing = reply.flash('nonexistent') as string[] // missing === [] ``` ``` -------------------------------- ### req.flash(type, ...message) — Set a Flash Message Source: https://context7.com/fastify/fastify-flash/llms.txt Stores one or more messages under a named type key in the session. Returns the total number of messages currently stored for that type. Messages accumulate across multiple calls with the same type. ```APIDOC ## req.flash(type, ...message) — Set a Flash Message ### Description Stores one or more messages under a named type key in the session. Returns the total number of messages currently stored for that type. Throws an error if no message is provided or if the session is not available. Messages accumulate — multiple calls with the same type append to the existing list. ### Method Signature `req.flash(type: string, ...message: any[])` ### Parameters - **type** (string) - Required - The type key for the flash message (e.g., 'error', 'warning', 'info'). - **...message** (any[]) - Required - One or more messages to store. Can be strings, arrays of strings, or formatted strings using `util.format` syntax. ### Returns - (number) - The total number of messages currently stored for the given type. ### Examples ```typescript // Single string message const count1 = req.flash('error', 'Invalid credentials') // count1 === 1 // Multiple messages in one call using an array const count2 = req.flash('warning', ['Username is required', 'Password is required']) // count2 === 2 // util.format-style interpolation req.flash('info', 'Hello %s, you have %d new messages', 'Alice', 3) // stored as: "Hello Alice, you have 3 new messages" // Accumulating multiple calls of the same type req.flash('notice', 'Last login: yesterday') req.flash('notice', 'New feature available') // session now has notice: ["Last login: yesterday", "New feature available"] ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.