how to stop django channels from connecting on every page ?

Hi, so for the past week was learning django channels, and have succesfuly integrated it with my app, and everything works fine.

the notifications show up
the like/unlike button works as well
and also the follow/unfollow a user also works

but only thing is that on every page it connects the websocket

is there a way to only connect it once the user logs in ? and keep the connection till the user is browsing the website or is in the session.

i know i can just use the JS file only on the pages i want, but i want the notifications JS file on the base html, so the user gets live notifications no matter which page they are.

My js file (This is my like a post file)

var surfing_user = document.getElementById("user_surfing").getAttribute("value")

if (surfing_user !== "AnonymousUser") {

if(document.querySelector('.flexbox-container') !== null){

const like_unlikeSocket = new WebSocket(
    'ws://' + '0.0.0.0:8000' +
    '/ws/like_unlike_a_post/'
  );
  
  like_unlikeSocket.onopen = function(e) {
    console.log("like_unlike_a_post WebSocket connection established!");

    const container = document.querySelector('.flexbox-container');
    container.addEventListener('click', function(event) {

        if (event.target.matches('[name="item-id"]')) {
            const retailer_id = event.target.value
            const clickedBtn = document.getElementById(`like-unlike-${retailer_id}`)

            // Send some data over the WebSocket
            like_unlikeSocket.send(JSON.stringify({
                "retailer_id": retailer_id,
                }));
            
            // GET some data over the WebSocket
            like_unlikeSocket.onmessage = function(e) {
                var data = JSON.parse(e.data)

                clickedBtn.innerHTML = `${data.no_of_likes} <i class="fa fa-heart small-heart"></i>`
                
                }
            

        }



    })

  
}
}
}

Loading a new page causes the old page - including the JavaScript running on that page - to go out of scope. Therefore, the old connection gets broken. When the new page is loaded, the new JavaScript on the new page reconnects.

If you want to ensure a consistent connection, you need to build an SPA or SPA-like app. This means you don’t do full-page loads, you use JavaScript and AJAX to load portions of the page as-needed.
(We do this using HTMX - it works extremely well for us.)

1 Like

thanks i tought i could store the django channels connection a session, so dont have to connect everytime a new page is loaded

will check out htmx,thanks

A websocket is a (type of) tcp network socket, it’s not just “data” representing a connection. It can’t be “saved” or “persisted”.