The
app.keys
property in Koa.js is used for setting a set of secret keys that are used to sign cookies and other data that require cryptographic integrity. These keys are used as a secret to generate cryptographic signatures for the data, ensuring that the data has not been tampered with during transmission.
Here's how the app.keys property is typically used :1. Setting app.keys : Set the
app.keys
property to an array of secret keys. These keys should be kept secret and should not be shared. It's common to use a set of randomly generated strings or other secure methods to create these keys.
const Koa = require('koa');
const app = new Koa();
// Set the app.keys property with an array of secret keys
app.keys = ['key1', 'key2', 'key3'];
// Your Koa application setup?
2. Signing Cookies : When you set cookies in your Koa application, the
app.keys
are used to sign the cookies. This signature is then included with the cookie data. When the client sends the cookie back to the server, the server can verify the integrity of the cookie by checking its signature against the
app.keys
.
app.use(async (ctx, next) => {
// Set a signed cookie
ctx.cookies.set('user', 'john_doe', { signed: true });
await next();
});?
In this example, the
signed: true
option indicates that the cookie should be signed using the
app.keys
.
3. Accessing Signed Cookies : When accessing cookies in subsequent requests,
Koa.js
automatically verifies the signature using the
app.keys
. This ensures that the cookie data has not been tampered with since it was set.
app.use(async (ctx, next) => {
// Access the signed cookie
const user = ctx.cookies.get('user', { signed: true });
// Use the user data
console.log('User:', user);
await next();
});?
When retrieving the cookie using
ctx.cookies.get('user', { signed: true })
, Koa.js will automatically verify the signature using the
app.keys
before providing access to the cookie data.