SirBT
SirBT

Reputation: 1698

Why am I not able to retrieve the express-session successfully saved?

Why isn't my express-session persisting.

My sessions are set in a server side file called 'payment_router.js' with the following contents:

const express = require('express');
const router = express.Router();
const { initiatePayment } = require('../routes/paymentProcessor'); // Ensure the path is accurate
const { v4: uuidv4 } = require('uuid'); // For generating unique references
require('dotenv').config();

// Route to handle payment initiation
router.post('/pay', async (req, res) => {

req.session.advertFormData = {
    advertName: req.body.advertName,
    chosenPackageName: req.body.chosenPackageName,
    daterange: req.body.daterange,
    .
    .
    .

};

req.session.save((err) => {
    if (err) {
        console.error('Error saving session:', err);
    }
    console.log('Session saved successfully with advertFormData 01:', req.session.advertFormData);
});

console.log('###################:-----> 00 ' ,req.sessionID);
console.log('###################:-----> 11 ' ,req.session);
console.log('###################:-----> 22 ' ,req.session.advertFormData);
.
.
.
 

This logs out the following:

[1] ###################:-----> 00  ZU7Nix6vTjdByILuv-SAuJ-vI7YGcGHj
[1] ###################:-----> 11  Session {
[1]   cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
[1]   passport: { user: '62fb82ac74bcc4de938c3592' },
[1]   flash: {},
[1]   advertFormData: {
[1]     advertName: 'Testing payments',
[1]     chosenPackageName: 'MVP',
[1]     daterange: '01/01/2025 - 02/01/2025',
.
.
.
[1] ###################:-----> 22  {
[1]   advertName: 'Testing payments',
[1]   chosenPackageName: 'MVP',
[1]   daterange: '01/01/2025 - 02/01/2025',
[1]   locationArray: [
[1]     '[{"zone":"Siaya, Kenya","lat":"0.05615","lng":"34.28829"},{"zone":"Surat (Soorat), Gujarat, India","lat":"21.1859","lng":"72.83662"}]',
[1]     ''
[1]   ],
[1]   CTAButtonName: 'Buy now',
.
.
.

Session saved successfully with advertFormData 01: {
[1]   advertName: 'Testing payments',
[1]   chosenPackageName: 'MVP',
[1]   daterange: '01/01/2025 - 02/01/2025',
[1]   locationArray: [
[1]     '[{"zone":"Siaya, Kenya","lat":"0.05615","lng":"34.28829"},{"zone":"Surat (Soorat), Gujarat, India","lat":"21.1859","lng":"72.83662"}]',
[1]     ''
.
.
.


[1] Session saved successfully with advertFormData: 02 {
[1]   advertName: 'Testing payments',
[1]   chosenPackageName: 'MVP',
[1]   daterange: '01/01/2025 - 02/01/2025',
[1]   locationArray: [
[1]     '[{"zone":"Siaya, Kenya","lat":"0.05615","lng":"34.28829"},{"zone":"Surat (Soorat), Gujarat, India","lat":"21.1859","lng":"72.83662"}]',
[1]     ''
[1]   ],
.
.
.

Later when I try to retrieve the session in another server side file called 'paymentSuccessful_Router.js' file, the sessions seem empty.

Following are the contents:

const express = require('express');
const router = express.Router();

router.get('/successful', (req, res) => {    

        const advertFormData = req.session.advertFormData || {
            advertName: '',
            companyEmail: '',
            chosenPackageName: '',
            daterange: '',
            locationArray: [],
            CTAButtonName: '',
            CTA_Link: '',
            dayArray: [],
            timesArraySettingToSave: [],
            phone: '',
            amount: '',
            scheduledDays: '',
            scheduledDays_andTimes: '',
        };


        console.log('Advert Form Data: 0', advertFormData); 
        console.log('Advert Form Data: 1', req.session.advertFormData);

And this logs out the following:

1] Advert Form Data: 0 {
[1]   advertName: '',
[1]   companyEmail: '',
[1]   chosenPackageName: '',
[1]   daterange: '',
[1]   locationArray: [],
[1]   CTAButtonName: '',
[1]   CTA_Link: '',
[1]   dayArray: [],
[1]   timesArraySettingToSave: [],
[1]   phone: '',
[1]   amount: '',
[1]   scheduledDays: '',
[1]   scheduledDays_andTimes: ''
[1] }
[1] Advert Form Data: 1 undefined

What do I have to do to get this to work?

Following is the contents of my app.js file in the context of the express-session.

const session = require('express-session');
// Session configuration
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    // resave: false,
    // saveUninitialized: false,
    // store: MongoStore.create({
    //   mongoUrl: process.env.MONGODB_URI,
    //   ttl: 14 * 24 * 60 * 60,
    //   autoRemove: 'native',
    // }),
    // cookie: {
    //   secure: process.env.NODE_ENV === 'production',
    //   httpOnly: true,
    //   maxAge: 14 * 24 * 60 * 60 * 1000,
    // },
    // name: 'driverSession',
  })
);

// Example CORS configuration
app.use(cors({
  origin: 'http://localhost:4000', // Replace with your frontend's URL
  credentials: true,              // Allows cookies/session sharing
}));
app.use(passport.session());

The code that requests for the GET /successful isnt a client side code but rather a servers side called 'paymentCallbackRouter.js' and following are its code contents:

router.get('/callback', async (req, res) => {
    console.log('## Received callback request:', req.query);

    const { OrderTrackingId, OrderMerchantReference } = req.query;

    // Validate callback parameters
    if (!OrderTrackingId || !OrderMerchantReference) {
        console.error('Missing callback parameters:', req.query);
        return res.status(400).json({ error: 'Invalid callback request' });
    }

    console.log('## Processing payment callback for:', { OrderTrackingId, OrderMerchantReference });

    try {
        // Simulate payment verification (replace with actual verification logic)
        const isPaymentSuccessful = true; // Example: Replace with actual logic to verify payment

        // Save the payment status (e.g., success or failure) in session
        req.session.paymentStatus = isPaymentSuccessful ? 'success' : 'failure';
        req.session.orderTrackingId = OrderTrackingId; // Save the OrderTrackingId

        if (isPaymentSuccessful) {
            console.log('Payment verification successful:', { OrderTrackingId });
            return res.redirect(`${AppURL}/paymentSuccessful/successful?OrderTrackingId=${OrderTrackingId}`);
        } else {
            console.warn('Payment verification failed:', { OrderTrackingId });
            return res.redirect(`${AppURL}/paymentSuccessful/failure?OrderTrackingId=${OrderTrackingId}`);
        }
    } catch (error) {
        console.error('Error processing callback:', error.message);
        return res.status(500).json({ error: 'Callback processing failed' });
    }
});

Upvotes: 0

Views: 26

Answers (0)

Related Questions