SignInWithRedirect Best Practices

This guide outlines best practices to make SignInWithRedirect work properly.

Before you continue, it is advised to configure redirect URIs. Click Me

Firebase has different options for making redirect work. each option depends on your app use case and how you host your app. fell free to visit firebase docs for more options. In this guide, we will discuss two options that can be applied so TernSecure can handle the redirect flawlessly.

  1. Proxy Auth Request to firebaseapp.com
  2. the use of authDomain as custom domain.
  3. use signInWithPopup() instead of signInWithRedirect().

For more detailed information, refer to Firebase docs Best Practices for SignInWithRedirect flows or if you prefer to Google Google Cloud Identity Platform - Redirect Best Practices.

1. Proxy Auth Request to firebaseapp.com

If your not hosting your app on firebase hosting.

When using Firebase Authentication with redirect flows, it's essential to ensure that the redirect URIs are correctly configured. One common approach is to proxy authentication requests to the firebaseapp.com domain associated with your Firebase project.

In Next.js applications, you can use the rewrites configuration in next.config.ts to proxy authentication requests to Firebase:

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async rewrites() {
    return [
      {
        source: "/__/auth/:path*",
        destination: "https://your-project-id.firebaseapp.com/__/auth/:path*",
      },
      {
        source: "/__/firebase/:path*",
        destination:
          "https://your-project-id.firebaseapp.com/__/firebase/:path*",
      },
    ];
  },
};
proxy.ts
import {
  ternSecureProxy,
  createRouteMatcher,
} from "@tern-secure/nextjs/server";

const publicPaths = createRouteMatcher([
  "/sign-in(*)",
  "/__/auth/(.*)", 
  "/__/firebase/(.*)", 
]);

export const config = {
  matcher: [
    "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    "/(api|trpc)(.*)",
  ],
};

export default ternSecureProxy();

2. Use signInWithPopup() Instead of signInWithRedirect()

if you are not hosting on Firebase hosting, you will still need to config proxy reverse as shown in option 1. TernSecure will handle the redirect automatically when choose mode 'popup ' in any signin method.

First, create signInWithSocialLogin function and pass the necessary parameters. TernSecure will handle the rest.

signInWithSocialLogin function
import { useSignIn } from "@tern-secure/nextjs";

const { signIn } = useSignIn();

const signInWithSocialLogin = async (
  provider: string,
  customOptions: SocialProviderOptions
) => {
  const res = await signIn?.withSocialProvider(provider, {
    mode: customOptions.mode || "popup",
    customParameters: customOptions.customParameters,
    scopes: customOptions.scopes,
  });

  if (res?.status === "error") {
    setFormError({
      status: "error",
      message: res.message,
      error: res.error,
    });
  }

  if (res?.status === "success") {
    createActiveSession({ session: res.user, redirectUrl: afterSignInUrl });
  }
};

Then, create provider function. define provider and mode as 'popup' to use popup mode.

SignInWithGoogle - mode: popup
const signInWithGoogle = () => {
  signInWithSocialLogin("google", {
    mode: "popup",
    customParameters: {
      access_type: "offline",
      login_hint: "user@example.com",
      prompt: "select_account",
    },
  });
};

3. Use authDomain as Custom domain

This options work only if you are hosting your app on firebase hosting.

Simply add authDomain in the Firebase config object. as we discussed in initialization, add the firebase object in environment variables. make sure to include the authDomain variable. when included TernSecure instance initialize firebase with the env variables. therfore authDomain will be considere as custom domain when using redirect.

.env
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=domain-that-serve-your-app

Last updated on