Me and my friend is working on mobile app project.
Our stack is:
Fastify with TRPC, next js for admin panel, kotlin multiplatform for apps.
I know react next and fastify/trpc. friend is mobile dev.
I have created fastify app and deployed on :(free tier)
https://mybackendprojectname.onrender.com
which is working fine.
while my friend working on mobile app I created admin panel in nextjs(14) with app router and deployed on vercel and its running on :(free tier)
https://myadminpanelname.vercel.app/
my problem is when i was doing development for admin panel in localhost:3000 for next and localhost:8080 for server, I was setting up cookie with name __Secure-myproject.auth-token=”jtw-secure-token-long-long-long”, on successful login response for admin panel(Firebase Login). that cookie will be used to extract token and include in authorization header and will verify token on each api req as well as for my next js middleware to keep user signed in. user’s auth context is in also zustand from the beginig from success login call.
but when i deploy both apps on different platforms with different urls, my admin panel is not redirecting me on /home after success login and i checked cookie it it’s there for first time but disappear when i refresh page.
my code snippets to look:
cookie config:
export const cookieConfig = {
authTokenName: '__Secure-myproject.auth-token',
default: {
maxAge: 7 * 24 * 60 * 60,
httpOnly: EnvConfig.NODE_ENV === 'production',
secure: EnvConfig.NODE_ENV === 'production',
sameSite: 'none',
path:'/'
} satisfies FastifyCookieOptions['parseOptions']
}
My server file:
server.register(fastifyCors, {
origin: [
'http://localhost:3000',
'https://mybackendprojectname.onrender.com',
'https://vercel.app',
'https://myadminpanelname.vercel.app/'
],
allowedHeaders: ['Content-Type', 'Authorization'],
methods: ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'],
credentials: true
})
server.register(fastifyCookie, {
secret: EnvConfig.JWT_AUTH_SECRET,
parseOptions: cookieConfig.default,
logLevel: 'warn',
hook: 'onRequest'
})
my next js middleware and login snippets:
export function middleware(request: NextRequest) {
const authToken =
(request.cookies.get('__Secure-myproject.auth-token')
?.value as unknown as string) ?? ''
const authRoutes = ['/', '/forgot-password']
const publicRoutes = ['/faq']
if (publicRoutes.includes(request.nextUrl.pathname)) {
return NextResponse.next()
}
if (authRoutes.includes(request.nextUrl.pathname)) {
if (authToken) {
return NextResponse.redirect(
new URL(authConfig.defaultAuthRedirect, request.url)
)
}
return NextResponse.next()
}
if (!authToken) {
return NextResponse.redirect(
new URL(authConfig.defaultUnathRedirect, request.url)
)
}
return NextResponse.next()
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)'
]
}
and
const GoogleLoginButton = () => {
const router = useRouter()
const { setUser } = useAuthStore()
const { mutateAsync: doGoogleLoginVerification } =
trpcClient.auth0.googleLogin.useMutation({})
const handleGoogleLogin = async () => {
try {
// firebase returns info object with token and other things
const userCreds = await LoginWithGoogle()
// extract id token from res object
const idToken = await userCreds.user.getIdToken()
// send id token to server so admin sdk can verify
const user = await doGoogleLoginVerification({ idtoken: idToken })
setUser({
id: user.id,
name: user.name,
email: user.email,
authToken: user.authToken
})
router.replace('/home')
} catch (error: any) {
console.log('Google Login Error ::', error)
}
}
return (
Login button ui.....
)
}
all code is working fine for local host with cookie flow. when i deploy for for testing (node_env=production), cookie is somehow not working as it should be.
can someone please guide me where am I missing something for deployed apps.
Jeet Patel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.