Next.js Discord

Discord Forum

Set cookie on server component

Unanswered
Batimius posted this in #help-forum
Open in Discord
Hello there. I'll make this short. In essence, I am making a custom OAuth system. The user goes to /auth/login, they are then redirected to Google's OAuth portal to sign in, and then they are redirected back to /auth/authCallback, where it takes the code, creates / gets the account, generates a session token, and supposingly sets it. Up until the generation of the session token is something that I have accomplished, but I am failing to find how I'd set the token to the client. If anyone can help, that would be amazing. Here's my code:
// Import \\

import { redirect } from 'next/navigation'
import { Metadata, NextApiResponse } from 'next'
import { authenticateWithOAuth } from '@/lib/dbHandler'

// Export \\

export const metadata: Metadata = {
    title: 'Auth Callback - Top Anime Songs',
    description: 'Auth callback',
}

export default async function ResultsPage({ searchParams }: { searchParams: { [key: string]: string | string[] | undefined }}, req) {

    const code = searchParams.code

    if (code) {
        const sessionToken = await authenticateWithOAuth(code as string)
        // This is where I'd set the session token
    }

    redirect("/")
}

6 Replies

You can set them directly via the cookies function. You can see how you can do this here: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
@Batimius
@B33fb0n3 You can set them directly via the cookies function. You can see how you can do this here: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options <@347858411897225236>
I tried that, but I get the following error: Error: Cookies can only be modified in a Server Action or Route Handler. If I use 'use server' at the top, it tells me To use Server Actions, please enable the feature flag in your Next.js config..

Should I enable server actions, or should I just create an API endpoint to handle this instead?
But you are in a server Component, right?
@B33fb0n3 But you are in a server Component, right?
Yes, under page.tsx
@Batimius Yes, under page.tsx
Hm yea, I just read that is only available in route handlers or server actions, like you told me. I would build a actions.js, that I declare as use server and either create a set Cookie function or something similar or maybe combine it with some other backend functionality 👍