Next.js Discord

Discord Forum

not able to set cookie using res.setHeader says setHeader not available

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
import axios from "axios";
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { cookies } from "next/headers";
import { parse } from "cookie";
import { NextApiRequest, NextApiResponse } from "next";

type NextAuthOptionsCallback = (
  req: NextApiRequest,
  res: NextApiResponse,
) => NextAuthOptions;

export const authOptions: NextAuthOptionsCallback = (req, res) => {
  return {
    providers: [
      GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID || "",
        clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
        authorization: {
          params: {
            prompt: "consent",
            access_type: "offline",
            response_type: "code",
          },
        },
      }),
    ],
    callbacks: {
      async jwt({ token, user, account, profile, isNewUser }) {
        if (account) {
          const response = await axios.post(
            "http://localhost:8000/api/v1/daizy/login",
            {
              code: account?.id_token,
            },
            {
              headers: {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "http://localhost:3000",
              },
              withCredentials: true,
            },
          );
          console.log("response", response);
          const cookie = response.headers["set-cookie"];
          if (cookie) {
            res.setHeader("Set-Cookie", cookie);
          }

          token.userId = response.data.token;
        }
        return token;
      },
      async session({ session, token, user }) {
        if (typeof token.userId === "string") {
          session.user.id = token.userId;
        }
        return session;
      },
    },
    secret: process.env.NEXTAUTH_SECRET,
    session: {
      strategy: "jwt",
    },
  };
};

0 Replies