skip to Main Content

I’ve a user login system on node.js. When a user is logged in, I set a cookie to maintain the user session. When the user is logged out, I destroyed the cookie with the code below:

function userLogout(cookies, res) {
    let cookie = Object.values(cookies)
    , cookie1 = cookie[0]
    , cookie2 = cookie[1]
    ;

    res.setHeader(
        'Set-Cookie',
            ['cookie1=; max-age=0; path=/',
            'cookie2=; max-age=0; path=/']
    );

    res.writeHead(301, {
        Location: `./index.html`
    }).end();
}

The redirect code above is taken from this thread: How to redirect user's browser URL to a different page in Nodejs?

However, I’ve got this error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the client

It doesn’t have any problem when I set the cookie in similarity order.

Any idea how can I fixed this?

Please noted that I don’t use frameworks like Express, just a plain vanilla javascript.

2

Answers


  1. Chosen as BEST ANSWER

    I've fixed this. I just prevented node.js to do further processing with a simple code below:

    userLogout(cookies, res);
    return;
    

    That's it.


  2. function userLogout(cookies, res) {
        let cookie = Object.values(cookies)
        , cookie1 = cookie[0]
        , cookie2 = cookie[1]
        ;
    
        // Set the response headers
        res.setHeader(
            'Set-Cookie',
            ['cookie1=; max-age=0; path=/',
            'cookie2=; max-age=0; path=/']
        );
    
        // Send the redirect response
        res.writeHead(301, {
            Location: `./index.html`
        });
    
        // End the response
        res.end();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search