@hapi/cookie Cookie Authentication Plugin
repository·master·Indexed 42 days ago
https://github.com/hapijs/cookieA cookie authentication plugin for the hapi ecosystem used to manage cookie-based authentication and state. It provides a cookie authentication scheme and decorates the request object (defaulting to cookieAuth) to set, clear, and modify session data. Version 12.0.1 requires hapi >=20.0.0.
What's inside @hapi/cookie
- @hapi/cookie is a cookie authentication plugin designed to work seamlessly with the hapi web framework. While optimized for the hapi ecosystem, it is a standalone module that can be used with other web frameworks.
Register the @hapi/cookie plugin
masterTo use cookie-based authentication in Hapi, register the
@hapi/cookieplugin. This plugin sets up acookieauthentication scheme and decorates therequestobject with a decorator (defaulting tocookieAuth) to manage session state.Requirements:
hapi:>=20.0.0
await server.register({ plugin: require('@hapi/cookie'), options: { cookie: { name: 'sid', password: 'password-must-be-at-least-32-characters-long', encoding: 'iron' } } });Configure @hapi/cookie plugin options
masterWhen registering the plugin, you can provide an options object to configure cookie behavior.
cookie(Object, Required)Defines the underlying Hapi state configuration.
name(String): The name of the cookie. Defaults to'sid'.password(String): The password used for encryption (required).encoding(String): The encoding method. Defaults to'iron'.clearInvalid(Boolean): If true, the cookie is cleared if validation fails.
validate(Function, Optional)A function used to validate the session data. It receives
(request, session)and must return an object containing{ isValid: boolean }. You can optionally returncredentialsto override the authenticated credentials.keepAlive(Boolean)If
true, the cookie is re-set on every request to extend its life. This requirescookie.ttlto be set.redirectTo(String | Function | Boolean)Determines where to redirect the user if they are unauthenticated.
false: Returns an unauthenticated error.String: A static URI.Function: A function that receives therequestand returns a URI.
appendNext(String | Boolean | Object)If redirecting, this determines if the original URL is appended as a query parameter.
true: Appends?next=...false: Does not append.Object:{ raw: boolean, name: string }. Ifrawis true, it uses the raw request URL; otherwise, it uses the parsed pathname and search.nameallows customizing the query parameter key.
requestDecoratorName(String)The name of the decorator added to the
requestobject. Defaults to'cookieAuth'.{ cookie: { name: 'sid', password: 'your-secret-password', encoding: 'iron' }, validate: async (request, session) => { // validation logic return { isValid: true }; }, redirectTo: '/login', appendNext: 'returnTo' }Manage sessions with request.cookieAuth
masterThe plugin decorates the
requestobject with a method (defaulting tocookieAuth) to interact with the session cookie. This object provides methods to set, clear, and modify the session.set(session, value)Sets the session data.
- Full Session:
request.cookieAuth.set(sessionObject)sets the entire session and returns a state header. This updatesrequest.auth.artifacts. - Key-Value:
request.cookieAuth.set('key', 'value')updates a specific key within the existing session stored inrequest.auth.artifactsand returns a state header.
clear(key)Removes a specific key from the session or clears the entire session.
- Specific Key:
request.cookieAuth.clear('key')deletes the key from the session and returns a state header. - Full Clear:
request.cookieAuth.clear()setsrequest.auth.artifactstonulland unsets the cookie.
ttl(msecs)Updates the Time-To-Live for the cookie in milliseconds.
Note: These methods return a state header (via
h.state) which must be returned by your handler to actually apply the changes to the response.// In a Hapi handler server.route({ method: 'POST', path: '/login', handler: async (request, h) => { // Set the entire session const session = { userId: 123 }; return request.cookieAuth.set(session); } }); server.route({ method: 'POST', path: '/update-profile', handler: async (request, h) => { // Update a specific key in the existing session return request.cookieAuth.set('theme', 'dark'); } }); server.route({ method: 'POST', path: '/logout', handler: async (request, h) => { // Clear the entire session return request.cookieAuth.clear(); } });- Full Session: