Coder Social home page Coder Social logo

fastify-flash's Introduction

@fastify/flash

CI NPM version js-standard-style

The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.

This plugin is inspired by connect-flash.

Install

npm i @fastify/flash

Usage

Flash messages are stored in the session. First, we need to register the session plugin: @fastify/secure-session.

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
  }
})
fastify.register(fastifyFlash)

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"]}
})

Note on session plugin

@fastify/secure-session can be replaced by any session plugin as long as it:

  1. registers via the onRequest hook
  2. supports req.session as the session store

API

Set a flash massage(s)

Signature

req.flash(type: string, ...message: string[] | [string[]]): number

It can be called in three different ways:

  • req.flash('info', 'Welcome back')
  • req.flash('warning', ['username required', 'password required'])
  • req.flash('info', 'Hello %s', 'Jared') // will use util.format to format the string

req.flash returns the number of messages store with provided type.

Get a flash message(s)

signature

reply.flash(type?: string): { [k: string]: undefined | string[] } | string[]

It can be called in two different ways:

  • reply.flash() // returns all messages as object { [k: string]: undefined | string[] }
  • reply.flash('info') // returns array of messages that are stored with provided type

License

MIT

fastify-flash's People

Contributors

azure-pipelines[bot] avatar climba03003 avatar cristianossd avatar darkgl0w avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar fdawgs avatar fox1t avatar frikille avatar is2ei avatar jsumners avatar mcollina avatar rafaelgss avatar salmanm avatar uzlopak avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-flash's Issues

Flash messages are not stored in the session

Flash messages are supposed to be stored in the session for later display (for example to display in the next page after a redirection).

This plugins seems to only keep the messages in the current request, which kind of defeats the purpose (you can just send your message directly in the data then). Here is an example that shows the bug. When you navigate to /test, then to /test2, the flash message is not properly passed, whereas the session data is kept correctly.

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: "jdsqkfdjsklfjdslkfjdslkjfdsklflksdjfkljdsfkjlds",
  cookie: {
    // options from setCookie, see https://github.com/fastify/fastify-cookie
  }
});
fastify.register(fastifyFlash);

fastify.get("/test", (req, reply) => {
  req.flash("warning", ["username required", "password required"]);
  req.session.set("test", "testvalue");
  reply.send("test");
});
fastify.get("/test2", (req, reply) => {
  const warning = reply.flash("warning");
  const testValue = req.session.get("test");
  reply.send({ warning, testValue }); // {"warning":["username required","password required"]}
});

const start = async () => {
  try {
    await fastify.listen(3000);
    fastify.log.info(`server listening on ${fastify.server.address().port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};
start();

Type Script Support

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I am using this package for my cli generated typescript project but unable to use it.

Getting below error whenever i am trying to use req.flash method.

Property 'flash' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>'.ts

Here is my code of src/app.ts file

import type { FastifyCookieOptions } from '@fastify/cookie' 

fastify.register(import('@fastify/cookie'), {
          secret: 'my-secret',
          parseOptions: {}
} as FastifyCookieOptions)

fastify.register(import('@fastify/secure-session'), { 
       secret: 'my-secret',
       salt: 'my-secret',
      cookie: { path: '/', httpOnly: true }
})

fastify.register(import('@fastify/flash'))

here is the error handler i am trying to use req.flash method

fastify.setErrorHandler(async function (error, request: FastifyRequest, reply: FastifyReply) {
		request.log.error(error)
		let errors = [];
		const locales = await fastify.getLocaleMsg(request.headers.lang as string || 'en');
		if (error.statusCode === 429) {
			reply.code(429)
			error.message = locales.RATE_LIMIT_ERROR
		}
		if(error.code == 'FST_ERR_VALIDATION'){
			reply.code(400)
			error.message = locales.VALIDATION_ERROR
			errors = error.validation ? error.validation.map((error) => locales[error.message as string] ? locales[error.message as string] : error.message ) : []
		}

                request.flash('error', errors)

		error.message = error.message ? error.message : locales.SOMETHING_WENT_WRONG
		const accept = request.accepts()
		switch(accept.type(['json', 'html'])) {
			case 'json':
				reply.type('application/json').send({ msg: error.message , errors: errors })
				break
			case 'html':
			  	reply.type('text/html').send(`<b>${locales.SOMETHING_WENT_WRONG}</b> <br /> ${error.message}`)
			  	break
			default:
			  	reply.send(Boom.notAcceptable('unacceptable'))
			  	break
		}
		// reply.send(error)
	})

Flash object message

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

๐Ÿš€ Feature Proposal

Currently, the req.flash() function accepts two arguments: type: string and message: string[] | [ string[] ].

As i think, The req.flash() should accept object in second arguments and not only string[] | [ string[] ]

Motivation

Let's take an example that we can return a flash message to view which contain some errors and messages.
Currently if we using view engine render, and on fail validation, its so hard to return errors and message to view with just string[]

Example

So here's how we could you this in view.

const errors = { [property: string]: string[] | object } = {
  name: ['Name is required.'],
  email: ['Email is required.', 'Email must be valid.'],
  password: ['Password is required.', 'Password must be at least 8 characters long.'],
  address: {
    street: ['Street is required.'],
    city: ['City is required.'],
    zipcode: ['Zipcode must be valid.']
  }
};
-------------------------------------------------------------
req.flash('flashErrors', errors);

Where to put flash method

I was wondering if the best place to mount reply.flash() method was inisde a preHandler. My plan is to build a fastify-plugin that decorates reply method.

fastify not found, proceeding anyway

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

latest

Plugin version

latest

Node.js version

latest

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

latest

Description

Trying to import fastify-flash with
import flash from 'fastify-flash';
but getting notification. Is this plugin compatible with ESM?

Steps to Reproduce

Try to import with import flash from 'fastify-flash';

Expected Behavior

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.