koajs / session

Simple session middleware for koa
MIT License
902 stars 113 forks source link

ctx.session.isNew undefined #165

Open fengyuanzemin opened 5 years ago

fengyuanzemin commented 5 years ago

Example

dependencies

"dependencies": {
    "koa": "^2.6.2",
    "koa-session": "^5.10.1"
  }

index.js

const session = require('koa-session');
const Koa = require('koa');
const app = new Koa();

app.keys = ['some secret hurr'];

const CONFIG = {
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};

app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));

app.use(ctx => {
  // ignore favicon
  if (ctx.path === '/favicon.ico') return;

  let n = ctx.session.views || 0;
  ctx.session.views = ++n;

 // undefined
  console.log(ctx.session.isNew)

  ctx.body = n + ' views';
});

app.listen(3000);
console.log('listening on port 3000');
RichAyotte commented 5 years ago

@fengyuanzemin the code you posted here works fine.

I suspect that the middleware that threw the error ctx.session.isNew undefined was used before the koa session middleware was used and the order of your middleware matters when you use a custom store.

The following will not work as expected.

const sessions = {}
const CONFIG = {
  store: {
    async get(key) {
      return sessions[key]
    }
    , async set(key, value) {
      sessions[key] = value
    }
    , async destroy(key) {
      sessions[key] = null
    }
  }
}

app.use(async context => {
  console.log(context.session)
})
app.use(session(CONFIG, app))

You must use the session middleware first.

app.use(session(CONFIG, app))
app.use(async (context, next) => {
  console.log(context.session)
})
scambier commented 5 years ago

I have the same "issue". isNew is true on the first call, but undefined on all subsequent calls (once I set some data inside the session object)

import Koa from 'koa'
import BodyParser from 'koa-bodyparser'

const cors = require('@koa/cors')
const bodyParser = require('koa-bodyparser')
const session = require('koa-session')

const app = new Koa()
app.use(cors({
  credentials: true
}))
app.use(bodyParser())

app.keys = ['somekey']
app.use(session(app))

app.use(ctx => {
  console.log(ctx.session.isNew)
  ctx.session.foo = 'bar'
  ctx.status = 200
})

const port = 3000

app
  .use(BodyParser())
  .listen(port)
  .on('listening', () => {
    console.log(`Listening on port ${port}...`)
  })

I have a client-side app on port 8080, sending POST requests with axios.

import axios from 'axios'

export const http = axios.create({
  withCredentials: true,
  baseURL: 'http://localhost:3000'
})