#How to set cookies on a page?

6 messages · Page 1 of 1 (latest)

low salmon
#

I want to have a page (/login) where a state cookie will be set and after that the user should be redirected but it doesn't work. This is my code:

import { redirect, RedirectType } from "next/navigation";
import { cookies } from "next/headers";

import { COOKIE_NAME_PREFIX } from "@/constants/guidelines";
import { encode } from "@/lib/utils";

const generateRandomState = (): string => {
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};

const generateAuthorizationURL = (state: string): string => {
    const data = {
        client_id: process.env.CLIENT_ID,
        redirect_uri: `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback`,
        response_type: "code",
        scope: ["identify", "guilds", "email"].join(" "),
        state
    };

    return `https://discord.com/api/oauth2/authorize?${encode(data)}`;
};

export default function Page() {
    const state = generateRandomState();
    const authorizationURL = generateAuthorizationURL(state);

    cookies().set(COOKIE_NAME_PREFIX + "state", state, {
        secure: process.env.NODE_ENV === "production",
        httpOnly: true,
        sameSite: "lax",
        path: "/"
    });

    return redirect(authorizationURL, RedirectType.push);
}
proud charmBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

candid flower
coarse arrow
#

If he wanted to do it the way he typed out he would have to do really weird things with having a component that sets a cookie when it mounts then redirects, just a silly thing to try and do. What Joulev said is the way

somber walrus
#

just adding an interesting concoction into the mix: it's not possible because the next server already sent the headers and some HTML to the client right away before the RSC code is even executed, which makes it not possible to put set-cookie headers.

low salmon
#

Okay thanks guys. I’ll gonna do it with the route handler then 👍🏽