-1

I have a route to check if a user is logged in. It works well, but I don't understand what is the problem if I create a second route just below that calls it just to do the same thing. It seems like I can't access the cookie anymore in the second route, but I don't know why. Thanks for your help !

// This route works :
router.get('/loggedin', async (req, res) => {
    try {
        const token = req.cookies.jwt;
        console.log("token : " + token) // Token is correct here in loggedin route, but is undefined if I use the route below
        const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
        if (decodedToken) {
            res.send(true);
        }
        else {
            res.send(false);
        }
    }
    catch (err) {
        res.status(500).send(false);
    }
});

// This route calls the route above and doesn't work
router.get('/loggedinbyanotherway', async (req, res) => {
    const checking = await fetch(`${process.env.API_URL}:${process.env.PORT || 3000}/loggedin`)
    console.log(checking.ok) // Returns false
    const data = await checking.json()
    console.log(data) // Returns false
    res.send(data)
});
GinDev
  • 11
  • 3

1 Answers1

0

Your fetch request isn't providing any cookies, so how could the code handling the request read any cookies?

More to the point... This entire operation is unnecessary. Why make an HTTP request to the application you're already using? Instead, extract the functionality you want into a common function and just call that function from both routes. For example:

const isLoggedIn = (req) => {
  const token = req.cookies.jwt;
  const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
  if (decodedToken) {
    return true;
  } else {
    return false;
  }
};

router.get('/loggedin', async (req, res) => {
  try {
    res.send(isLoggedIn(req));
  }
  catch (err) {
    res.status(500).send(false);
  }
});

router.get('/loggedinbyanotherway', async (req, res) => {
  const checking = isLoggedIn(req);
  res.send(checking);
});

In the example it's not really clear why you need the second route or what else it offers, but I can only assume it's just a placeholder for some additional functionality you plan to add.

Either way, the point is that the application doesn't need to make an entire HTTP request to itself, since you're already in that application and have access to the same logic.

David
  • 208,112
  • 36
  • 198
  • 279
  • Thanks for your answer. The aim is to have an external function like : ``` const isConnected = () => { const checking = await fetch(`${process.env.API_URL}:${process.env.PORT || 3000}/loggedin`) return = await checking.json() } ``` I tried this first and it doesn't work (same problem as mentioned), so I tried to implement the function directly in the router file to see what is happening. I don't understand why the fetching instruction doesn't simply return the "true" value expected. – GinDev Dec 13 '22 at 12:45
  • The code is not readable in the comment, I'll edit my question so. – GinDev Dec 13 '22 at 12:46
  • @GinDev: How can the suggestion in this answer have the "same problem as mentioned"? The problem in the question is that the HTTP request isn't sending any cookies, so there's no way for the endpoint to read any cookies. This answer suggests to skip the HTTP request entirely, since it's unnecessary. Each endpoint here individually handles reading the cookie. When you test this approach, what specifically doesn't work as expected? – David Dec 13 '22 at 12:47
  • The cookie is already here. It is provided by another login route. When I test in Postman, the cookie is setted in the two routes. But /loggedin returns "true" and /loggedinbyanotherway returns "false". – GinDev Dec 13 '22 at 12:51
  • @GinDev: But you're *assuming* that `fetch` will automatically forward any cookies when it's invoked. This assumption is simply wrong. There is no documentation or example to support this assumption. When *the client* makes an HTTP request to `loggedinbyanotherway` then *the client* sends cookies. But when `loggedinbyanotherway` makes an HTTP request to `loggedin` in your code, *your code* isn't sending any cookies. But, once again, the point here is that you shouldn't be doing this in the first place. There's no reason for an application to make an HTTP request *to itself*. – David Dec 13 '22 at 12:53
  • "There's no reason for an application to make an HTTP request to itself." I totally agree with you. I'm just trying to understand what concept I didn't understood. And the point is here : "But then loggedinbyanotherway makes an HTTP request to loggedin in your code, your code isn't sending any cookies." I thought that http only cookies are automatically send everytime and everywhere. But this is not the case when using fetch if I understood it right :) – GinDev Dec 13 '22 at 12:58
  • @GinDev: *"I thought that http only cookies are automatically send everytime and everywhere."* - No. Cookies are not magic. They don't exist everywhere at all times. Each host (client or server) has to deliberately send them. And your code [isn't doing that](https://stackoverflow.com/q/34815845/328193). – David Dec 13 '22 at 13:05
  • Thank you very much for your responses. It becomes clearer. But let me insist to understand : in Postman, when I request /loggedin, it's return true. When I request /loggedinbyanotherway, it's return false. And when I request /loggedin again, it still returns true. So in the first route "const decodedToken = jwt.verify(token, process.env.JWT_SECRET);" will always have access to the cookie, but in the second route, it will be undefined, as if fetch lost the cookies (but it is visible in Postman in the /loggedinbyanotherway tab). I'm sorry but this is a confusing for me. – GinDev Dec 13 '22 at 15:36
  • @GinDev: *"as if fetch lost the cookies"* - It didn't "lose" the cookies. You didn't [**specify** any cookies](https://stackoverflow.com/q/34815845/328193). If you want your `fetch` request to include any additional information, such as cookies or other headers, then you need to include that in your code. At no point will your code guess what you meant for it to do and fill in the blanks for you. – David Dec 13 '22 at 15:38