i am doing a google login , then passing a jwt token in the form of cookies to the frontend broswer
this token is used by the middleware to pass in to the secured routes
the main problem is , the token is set as a cookie in the localhost , and frontend backend code is running fine
but when i am shifting to developmental https environment with both the frontend and backend ,
then my backend is producing the jwt , but my frontend is not showing up the token in the cookies section
i am using next js as my frontend
my login code
import { Router } from 'express';
import passport from 'passport';
import User from '../models/User'; // Ensure this path is correct for your project structure
import jwt from 'jsonwebtoken';
import cookie from 'cookie';
import dotenv from 'dotenv';
dotenv.config();
const router = Router();
//router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/creator', passport.authenticate('google-content-creator', {
accessType: 'offline',
prompt: 'consent',
scope: [
'profile',
'email',
// Add any other scopes needed for YouTube here
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl'
]
} as any));
router.get('/google/redirect', passport.authenticate('google-content-creator', { failureRedirect: '/login' }), async (req, res) => {
if (req.user) {
const { googleId, email, name } = req.user as any; // Type casting for simplicity
try {
// Check if the user already exists
let user = await User.findOne({ googleId });
if (user) {
user.isContentCreator = true;
await user.save();
} else {
user = new User({ googleId, email, name, isContentCreator: true });
await user.save();
}
// Create a token object
const tokenData = {
_id: user._id,
email: user.email,
googleId: user.googleId,
name:user.name
};
const tokenSecret = process.env.JWT_SECRET as string
const token = jwt.sign(tokenData, tokenSecret, { expiresIn: "1d" });
console.log("token",token)
// Set token in cookies
res.setHeader('Set-Cookie', cookie.serialize('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
maxAge: 60 * 60 * 24 // 24 hours
}));
const creatorId = user._id
console.log('Redirecting to dashboard of content creator...');
res.redirect(`${process.env.CREATOR_CLIENT_URL}/${creatorId}/contentCreatorDashboard`);
} catch (error) {
console.error('Error handling user login:', error);
res.status(500).send('Internal Server Error');
}
} else {
console.log('User authentication failed, redirecting to login...');
res.redirect('/login');
}
});
export default router;
my middleware code , in the frontend
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { cookies } from 'next/headers';
export async function middleware(request: NextRequest) {
const cookieData = cookies().getAll();
const token = cookieData.find(cookie => cookie.name === 'token')?.value;
const path = request.nextUrl.pathname;
// Adjust the paths as needed
const isPublicPath = ['/login', '/signup', '/verifyemail'].includes(path);
if (!token && !isPublicPath) {
// User is not logged in and trying to access a protected route
return NextResponse.redirect(new URL('/login', request.url));
}
// If the user is trying to access login-related routes but is already authenticated
if (token && isPublicPath) {
return NextResponse.redirect(new URL('/fetchUser', request.url));
}
// Allow the request to continue
return NextResponse.next();
}
export const config = {
matcher: [
`/:path*/contentCreatorDashboard`,
`/login`,
`/signup`,
`/verifyemail`,
`/test`,
`/:path*/campaigns`,
`/:path*/campaigns/campaignAnalytics/:path*`,
`/:path*/leaderBoard`,
`/fetchUser`,
'/:path*/leaderBoard/:path*'
], // Adjust based on your route requirements
};
i am expecting the token to show up in the application-cookie section of the browser , so that my middleware can read it and can pass so that i can get redirected to my secured routes
Prajyan Borah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.