salesforce / tough-cookie

RFC6265 Cookies and CookieJar for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sharing the same cookie jar throughout different Express routes

OwaisSiddiqui opened this issue · comments

commented

I created a tough-cookie cookie jar in one route (in a file). I want to share it with another route so that the cookies are stored in the other route (different file) so that using node-fetch doesn't start a new session (with the cookies cleared).

I tried using express-session and put the cookie jar in it but that does not work.

Code:

server.js:

const express = require('express')
const session = require('express-session')

const app = express()
const port = 3000

app.use(session({
    secret: 'secret-key',
    resave: false,
    saveUninitialized: true
}))
app.use('/email', require('./email'))
app.use('/login', require('./login'))

app.listen(port)

login.js:

const express = require('express')
const jsdom = require("jsdom")
const fetch = require('node-fetch')
const tough = require('tough-cookie')

const router = express.Router()
const { JSDOM } = jsdom
var cookieJar = new tough.CookieJar()

const handleRedirect = (response) => {
    // setCookie of response link and recurse if there is a new redirect link
}

router.post('/', (req, res) => {
    // Multiple node-fetch requests which require handleDirect
    // Set req.session.cookieJar = cookieJar on last node-fetch
}

email.js

const express = require('express')

const router = express.Router()

router.get('/', (req, res) => {
    // fetch a link which first requires to login (and sets the appropriate cookies)
    // returns login page and not the email information since cookies are not set
}
commented

Okay, I found a way to do it. In the email route, I had first had to deserialize the cookie jar from the req:

const tough = require('tough-cookie')
var cookieJar = null

tough.CookieJar.deserialize(req.session.cookieJar, (error, deserializedJar) => {
    if (error) throw new Error("Failed to deserialize.")
    cookieJar = deserializedJar
 })

and then set the cookie header for the node-fetch request using cookieJar.getCookieStringSync("<node-fetch URL>").