Coder Social home page Coder Social logo

Comments (11)

konstantinmuenster avatar konstantinmuenster commented on May 14, 2024 1

Ah, good spot! Try to move the router.push("/login"); call inside the logoutOnServer function like this:

const LogoutPage = () => {
  useEffect(() => {
    const logoutOnServer = async () => {
      const router = useRouter;
      try {
        await fetch(`${process.env.NEXT_PUBLIC_API}/users/logout`, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
        });
        router.push("/login");
      } catch (err) {
        console.log(err);
      }
    };
    logoutOnServer();
  }, []);
  return null;
};

Thus we make sure that we wait until the API request has been resolved. Only then we push to /login.

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024 1

that did it! i had just added a timeout in before you mentioned that, but i think just leaving it to happen after the fetch occurs makes more sens!

from notion-clone.

konstantinmuenster avatar konstantinmuenster commented on May 14, 2024

Hi! Hm, that's weird. Does it work if you add a try/catch to the logout function? Like this:

const logout = (req, res, next) => {
  const userId = req.userId;
  
  try {
    if (!userId) {
      const err = new Error("User is not authenticated.");
      err.statusCode = 401;
      throw err;
    }

    res.clearCookie("token", { domain: process.env.DOMAIN });
    res.status(200).json({
      message: "User successfully logged out.",
      userId: userId,
    });
  } catch (err) {
    next(err);
  }
};

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

@konstantinmuenster no luck for me so far! i tried doing that and the app still crashes when i try to log out and gives the error in the terminal that i pasted to you above! i'm trying to figure out why the cookie doesn't get cleared.

from notion-clone.

konstantinmuenster avatar konstantinmuenster commented on May 14, 2024

@sayemmh I'll have a look at it within the next days and try if I can reproduce it. You said the cookie is still there after visiting the logout route.. does the page crash completely or are you being redirected somehow?

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

@konstantinmuenster i just added some console.logs to try to understand the flow of the issue. from what i can tell, when i click logout, the users controller logout function runs (but for some reason the cookie does not get cleared). maybe the path needs to be specified or something in that res.clearCookie call.

login.js

export const getServerSideProps = (context) => {
  console.log("login getServerSideProps called!")
  const { token } = cookies(context);
  const res = context.res;
  console.log(token)
  console.log(res)
  if (token) {
    res.writeHead(302, { Location: `/account` });
    res.end();
  }
  return { props: {} };
};

here i have a console.log in login.js's getServerSideProps method that print the token (which should have been cleared if the res.clearCookie worked, right?). because there is still a token, i guess it goes into res.writeHead? i'm not understanding this part (new at node and express) but the next thing i see in the log is
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

oh and yes, it seems like it gets redirected to login.js for a tiny bit before the frontend crashes

from notion-clone.

konstantinmuenster avatar konstantinmuenster commented on May 14, 2024

I tried to reproduce the error but when I clone the repo and start the application it works fine for me. Maybe to narrow down where the error actually occurs, we can check in which step the app breaks:

  1. When you click on Logout, you are redirected to the /logout route.
  2. getServerSideProps in logout.js checks whether there is a cookie. If not, the component mounts.
  3. Once it is mounted, the useEffect hook runs and makes a request to the backend.
  4. Once the request has been made, the cookie is cleared, and you are redirected to the /login route.

Can you check to things:

  • What is the response from the API call to /users/logout?
  • Does the API request has a proper Cookie header and the response a proper Set-Cookie one?
  • Does it work if you comment out the router.push("/login"); line in logout.js?

I remember that I faced some cross-domain cookie issues while deploying. This also led to not setting and clearing the cookie properly. But if you run both frontend and backend on localhost, this should be no problem at all.

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

Hi, I deployed on localhost for both. I am able to 1) sign up (which redirects me to /pages), and 2) log out successfully. The issue happens when I login (now with my new user, not with sign up). It directs me to /pages, and then when I log out, the app crashes.

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

What do you mean by the response to /users/logout? That does not throw an error but I still think it is not properly clearing the cookie. This is the API request as I found it in logout.js, I didn't change anything, this is just how it was in the repo.

await fetch(`${process.env.NEXT_PUBLIC_API}/users/logout`, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
        });

When I comment out router.push("/login");, the app now doesn't crash but it sits at /logout

from notion-clone.

sayemmh avatar sayemmh commented on May 14, 2024

I think I just realized what's going on wrong. On the other times you push, there was a timeout...

setTimeout(() => {
      router.push("/login");
    }, 4000);

I think my API is very slow and /login was being pushed before the API call would ever actually complete. As soon as I put a timeout in now, it's been letting me log in and out over and over. Any tips on how to avoid this?

from notion-clone.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.