koajs / koajs/session

Is there any way to set cookie domain per request rather than per server launch?

Open
#188 6 comments 5 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
908
Forks
115
PR merge metrics
No merged PRs in 30d

Description

Right now I have the following code in my index.js:

```JavaScript
const Koa = require('koa');
const session = require('koa-session');

const app = new Koa();

app.use(
session(
{
key: SSID,
maxAge: SESSION_TTL,
rolling: true,
httpOnly: true,
store: SessionStore,
domain: DOMAIN,
},
app
)
);
```

The problem is, it sets domain once and for all and then passes that value to ctx.cookie.set() every time. What I need is customizable cookie domain based on request values like hostname or query etc. I can elaborate on the use case I need that for, if that's of any relevance. I don't see how can I do that currently, but I found a solution which basically creates new koa-session middleware on every request:

```JavaScript
app.use(async (ctx, next) => {
const { cookieDomain } = ctx.query;

await session(
{
key: SSID,
maxAge: SESSION_TTL,
rolling: true,
httpOnly: true,
store: SessionStore,
domain: cookieDomain || DOMAIN,
},
app
)(ctx, next);
});
```

This would work, but unfortunately 2 out of 3 properties defined [here](https://github.com/koajs/session/blob/master/index.js#L126) have configurable set to false implicitly, so on the second request I get "TypeError: Cannot redefine property: sessionOptions" error.

So, I have 3 questions:

1. Is there any way to achieve what I need with koa-session right now that I've missed?

2. If previous answer is "no", is there any real reason sessionOptions and [CONTEXT_SESSION] are non-configurable?

3. If previous answer is "no", can it be changed to configurable? What needs to be done for that (do I need to submit PR or something)?

Contributor guide

Open the contributing guide

Research direction

Read index.js around line 126, where sessionOptions and CONTEXT_SESSION are defined, and compare that behavior with the per-request middleware example in the issue. Determine whether cookie domains can be selected per request without redefining those properties; done should include a supported behavior or a clear maintainer decision about the required API change.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.