3

I'm very confused about how to get the current user with SSR to get some user data.

I've been using the context API with react, and it's been working so far, until I need SSR to get data from an API. I want to get the current user id, so I can get a token that is stored in Firestore.

Auth.js

export const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
    });
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
}

SSR

export async function getStaticProps() {
  const api = {
    auth: "token",
  };

  //fetch api

  return {
    props: {
      data,
    },
  };
}

1 Answer 1

7

Firebase SDKs are meant to be used on client side only so you won't be able to get current user on server side unless you set a cookie. Whenever a user logs in, you can call your API which will create a session cookie using Firebase Admin and set it.

app.post('/sessionLogin', (req, res) => {
  const idToken = req.body.idToken.toString();
  const expiresIn = 60 * 60 * 24 * 5 * 1000;

  return admin
    .auth()
    .createSessionCookie(idToken, { expiresIn })
    .then(
      (sessionCookie) => {
        const options = { maxAge: expiresIn, httpOnly: true, secure: true };
        res.cookie('session', sessionCookie, options);
        res.end(JSON.stringify({ status: 'success' }));
      },
      (error) => {
        res.status(401).send('UNAUTHORIZED REQUEST!');
      }
    );
});

You can read the session cookie in getServerSideProps and verify it to get user's UID:

const decoded = await admin.auth().verifySessionCookie(sessionCookie)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Is it possible to message you? Since I've never worked with the admin sdk before. I'm unsure how to setup your answer...
@Polle you can ask questions here or there's a Discord link in my profile.
const handleLogin = useCallback(async (e) => { e.preventDefault(); await signInWithRedirect(auth, provider); }, []); That's how I login. How would I put the session cookie code?
@Polle first you need to create an API route where you can add the code in my answer above. After the user logs in call that API which will add the cookie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.