Next.js Discord

Discord Forum

Help with Setting Session

Unanswered
Beveren posted this in #help-forum
Open in Discord
BeverenOP
I've set up custom Discord authentication. Once user is redirected to localhost, I've the json object that I need (user info basically).

console.log("User data in session:", req.session.user); // This will specifically log the user data
    
        //res.status(200).json("works");
        res.redirect('/');

But I can't get to save it globally so once user is redirected I can access the session and use it.

I'm using this "middleware", but I don't think it works:

import { NextApiRequest, NextApiResponse } from 'next';
import withSession from 'next-session';

const sessionConfig = {
  name: 'Discord session',
  secret: 'rKweJkORLDFP4w65AGlXEzsjbZ90RVLp',
  cookie: {
    maxAge: 7 * 24 * 60 * 60 * 1000, // Expires in 7 days
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: true,
  },
  rolling: true,
  resave: false,
  saveUninitialized: false,
};

const sessionMiddleware = withSession(sessionConfig);

const withSessionMiddleware = (handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {
    return async (req: NextApiRequest, res: NextApiResponse) => {
        await sessionMiddleware(req, res); // Call session middleware first.
        return handler(req, res); // Then call your handler.
    };
};


export default withSessionMiddleware;


This is the actualy API route that's called which gets user info as json object and redirects user to index page

import { NextApiRequest, NextApiResponse } from 'next';
import withSessionMiddleware from '../../../../utils/withSessionMiddleware'

interface NextApiRequestWithSession extends NextApiRequest {
  session?: any;  // Ideally, replace any with your session's type if you know it.
}

const redirect = async (req: NextApiRequestWithSession, res: NextApiResponse) => {

...logic...

export default withSessionMiddleware(redirect);


Log doesn't work
const { data: session, status } = useSession();
console.log("userdata", session?.user);

0 Replies