My fastify cookie is not persisting/working in Nextjs app

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.

New contributor

Jeet Patel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật