Hello supertokens, trying to implement social logi...
# support-questions-legacy
f
Hello supertokens, trying to implement social login with github on nextjs using custom UI, and I'm getting some errors in the sign-in process. However, he app appears to auto refresh the session and auto login the user just fine, it's just the manual sign in/up flow that isnt working. Previously, I first tried with pre-built UI and everything worked smoothly. Getting this error in the server terminal
Copy code
⨯ Error: Getting userInfo failed with 401: {"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}
...message too long to include all my text. Will add more posts to show my code, one sec.
I have a signin/out page that checks for session and then renders a
<SignInComponent />
when user is not signed in.
Copy code
ts
"use client";

import { Box, Button } from "@mui/material";
import { getAuthorisationURLWithQueryParamsAndSetState } from "supertokens-web-js/recipe/thirdparty";

const SignInComponent = () => {
    async function githubSignInClicked() {
        try {
            const authUrl = await getAuthorisationURLWithQueryParamsAndSetState(
                {
                    thirdPartyId: "github",
                    frontendRedirectURI:
                        "http://localhost:3000/auth/callback/github",
                }
            );

            console.log("authUrl\n", authUrl);
            // prints https://github.com/login/oauth/authorize?client_id=<REDACTED>&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fcallback%2Fgithub&response_type=code&scope=read%3Auser+user%3Aemail&state=<REDACTED>

            window.location.assign(authUrl);
        } catch (err: any) {
            if (err.isSuperTokensGeneralError === true) {
                // this may be a custom error message sent from the API by you.
                window.alert(err.message);
            } else {
                window.alert("Oops! Something went wrong.");
            }
        }
    }

    return (
        <Box display={"flex"}>
            <Button variant="contained" onClick={githubSignInClicked}>
                LOG IN WITH GITHUB
            </Button>
        </Box>
    );
};

export default SignInComponent;
Here is my callback page set to
/auth/callback/github
Copy code
ts
"use client";

import { useEffect } from "react";
import { signInAndUp } from "supertokens-web-js/recipe/thirdparty";

export default function AuthGitHub() {
    useEffect(() => {
        async function handleGitHubCallback() {
            try {
                const response = await signInAndUp();

                if (response.status === "OK") {
                    console.log(response.user);
                    if (
                        response.createdNewRecipeUser &&
                        response.user.loginMethods.length === 1
                    ) {
                        // sign up successful
                    } else {
                        // sign in successful
                    }
                    window.location.assign("/home");
                } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") {
                    // ...
                } else {
                    // ...

                    window.alert(
                        "No email provided by social login. Please use another form of login"
                    );
                    window.location.assign("/auth"); // redirect back to login page
                }
            } catch (err: any) {
                if (err.isSuperTokensGeneralError === true) {
                    // this may be a custom error message sent from the API by you.
                    window.alert(err.message);
                } else {
                    window.alert("Oops! Something went wrong.");
                }
            }
        }
        handleGitHubCallback();
    }, []);

    return null;
}
FrontendConfig
Copy code
ts
import ThirdPartyReact, { Google, Facebook } from 'supertokens-auth-react/recipe/thirdparty'
import SessionReact from 'supertokens-auth-react/recipe/session'
import { appInfo } from './appInfo'
import { SuperTokensConfig } from 'supertokens-auth-react/lib/build/types'
import { useRouter } from "next/navigation";

const routerInfo: { router?: ReturnType<typeof useRouter>; pathName?: string } = {};

export function setRouter(
    router: ReturnType<typeof useRouter>,
    pathName: string,
) {
    routerInfo.router = router;
    routerInfo.pathName = pathName;
}

export const frontendConfig = (): SuperTokensConfig => {
    return {
        appInfo,
        recipeList: [
            ThirdPartyReact.init({
                signInAndUpFeature: {
                    providers: [
                        ThirdPartyReact.Github.init(),
                    ],
                },
            }),
            SessionReact.init(),
        ],
        windowHandler: (original) => ({
            ...original,
            location: {
                ...original.location,
                getPathName: () => routerInfo.pathName!,
                assign: (url) => routerInfo.router!.push(url.toString()),
                setHref: (url) => routerInfo.router!.push(url.toString()),
            },
        }),
    }
}
backend config
Copy code
ts
import SuperTokens from "supertokens-node";
import ThirdPartyNode from 'supertokens-node/recipe/thirdparty'
import SessionNode from 'supertokens-node/recipe/session'
import { appInfo } from './appInfo'
import { TypeInput } from "supertokens-node/types";
import Dashboard from "supertokens-node/recipe/dashboard";
import UserRoles from "supertokens-node/recipe/userroles";

export const backendConfig = (): TypeInput => {
    return {
        framework: "custom",
        supertokens: {
            connectionURI: "redacted",
            apiKey: "redacted",
        },
        appInfo,
        recipeList: [
            ThirdPartyNode.init({
                signInAndUpFeature: {
                    providers: [{{
                        config: {
                            thirdPartyId: "github",
                            clients: [{
                                clientId: "redacted",
                                clientSecret: "redacted"
                            }]
                        }
                    }, 
          ....
            UserRoles.init(),
            Dashboard.init(),
            SessionNode.init({
                exposeAccessTokenToFrontendInCookieBasedAuth: true,
            }),
        ],
        isInServerlessEnv: true,
    }
}
r
is the signinup API getting called twice on the callback page?
cause in react dev, strict mode, useEffects happen twice
which means that the firstt signinup will succeed and get a session, and then second one will fail.
f
OHHHH, amazing, useEffect trips me over once again... added a useRef condition checek and forced it to run once. Now the sign in flow works! Cheers 🥳
r
great!