#Able to login without any problems but getting error logs in console

10 messages · Page 1 of 1 (latest)

velvet bay
#

Hi I am trying to login with google using SSR. The thing is working properly but I am getting error in the console that says:

Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?client_id=751249844538-3ipogqq7glr6cigf74vj4jkuqqu8vllu.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fcloud.appwrite.io%2Fv1%2Faccount%2Fh%5C%2Fcallback%22%2C%22failure%22%3A%22http%3A%5C%2F%5C%2Flocalhost%3A3000%5C%2Fauth%5C%2Fsignup%3Ferror%3Dauth_failed%22%2C%22token%22%3Atrue%7D&response_type=code' (redirected from 'http://localhost:3000/api/auth/oauth/google?_rsc=109sb') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
fetch-server-response.ts:106 
        
        
        GET https://accounts.google.com/o/oauth2/v2/auth?client_id=751249844538-3ipogqq7rruruigf74vj4jkuqqu8vllu.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fcloud.appwrite.io%2Fv1%2Faccount%2Fsessions%2Foauth2%2Fcallback%2Fgoogle%2F66952cc200353575435a1&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&state=%7B%22success%22%3A%22http%3A%5C%2F%5C%2Flocalhost%3A3000%5C%2F3A3000%5C%2Fauth%5C%2Fsignup%3Ferror%3Dauth_failed%22%2C%22token%22%3Atrue%7D&response_type=code net::ERR_FAILED
fetchServerResponse 
app-index.tsx:25  Failed to fetch RSC payload for 

this is my folder structure

this is my folder structure
-- app/
      -- api/
            -- auth/
                 -- login/
                 -- oauth/
                       -- [provider]/
                             -- route.ts
                       -- callback/
                                 -- route.ts
      -- auth
junior swallow
velvet bay
#

I am trying to add multiple Oauth login.
the link for my button looks like this /api/auth/oauth/google
So when the user visits the url above the code in [provider]/route.ts runs
this is the code for [provider]/route.ts

export const dynamic = "force-dynamic";
export const runtime = "edge";

import { createAdminClient } from "@/lib/server/appwrite";
import { redirect } from "next/navigation";
import { NextRequest, NextResponse } from "next/server";
import { OAuthProvider } from "node-appwrite";

function capitalizeFirstLetter(string: string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
export async function GET(
  request: NextRequest,
  { params }: { params: { provider: string } }
) {
  const { provider } = params;
  // get origin from request
  const origin = request.nextUrl.origin;
  try {
    const { account } = await createAdminClient();
    const url = await account.createOAuth2Token(
      OAuthProvider[
        capitalizeFirstLetter(provider) as keyof typeof OAuthProvider
      ],
      `${origin}/api/auth/oauth/callback`,
      `${origin}/auth/signup?error=auth_failed`
    );
    console.log(
      "OAuth URL:",
      url,
      "for provider:",
      provider,
      "origin:",
      origin
    );

    return NextResponse.redirect(url);
  } catch (err) {
    console.error(err);
    return NextResponse.json(
      { error: "An unexpected error occurred" },
      { status: 500 }
    );
  }
}

#

this is the code for callback/route.ts

import { NextRequest, NextResponse } from "next/server";
import { createAdminClient } from "@/lib/server/appwrite";
import { cookies } from "next/headers";

export async function GET(request: NextRequest) {
  console.log("OAuth callback triggered");
  const searchParams = request.nextUrl.searchParams;
  const userId = searchParams.get("userId");
  const secret = searchParams.get("secret");
  if (!userId || !secret) {
    console.error("Missing userId or secret in callback");
    return NextResponse.redirect(
      `${process.env.NEXT_PUBLIC_APP_URL}/auth/error`
    );
  }
  try {
    const { account } = await createAdminClient();
    console.log("Session client created");

    const session = await account.createSession(userId, secret);
    console.log("Session retrieved:", session);
    cookies().set("my-custom-session", session.secret, {
      path: "/",
      httpOnly: true,
      sameSite: "strict",
      secure: true,
    });

    if (session) {
      console.log("Session created successfully, redirecting to dashboard");
      return NextResponse.redirect(
        `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`
      );
    } else {
      console.log("No session found, redirecting to login with error");
      return NextResponse.redirect(
        `${process.env.NEXT_PUBLIC_APP_URL}/auth/signin?error=auth_failed`
      );
    }
  } catch (error) {
    console.error("Error handling OAuth callback:", error);
    return NextResponse.redirect(
      `${process.env.NEXT_PUBLIC_APP_URL}/auth/signin?error=auth_failed`
    );
  }
}

velvet bay
#

Ok now I understand the problem. It is Nextresponse.redirect(url) in [provider]/route.ts is causing the error I have moved the code to /lib/server/oauth.ts with redirect from next/navigation and it works
here is the code for oauth.ts

// src/lib/server/oauth.js
"use server";

import { createAdminClient } from "@/lib/server/appwrite";
import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { OAuthProvider } from "node-appwrite";

export async function signupWithGoogle() {
  const { account } = await createAdminClient();

  const origin = headers().get("origin");

  const redirectUrl = await account.createOAuth2Token(
    OAuthProvider.Google,
    `${origin}/api/auth/oauth/callback`,
    `${origin}/auth/signup?error=auth_failed`
  );

  return redirect(redirectUrl);
}

#

But shouldn't it work in [provider]/route.ts too

junior swallow
#

@smoky swan can you provide some insight into this problem with creating an OAuth2 token in NextJS?

smoky swan
junior swallow