Restrict client from html page using javascript

I serve a HTML page, which presents within my users-authentication system.

The HTML page should be unreachable when non-authenticated client tries to access it.

So, I have the following JS code:

let isAuthenticated = false;
let username;

(async () => {
    // Retrieve username if logged-in
    try {
        const serverResponse = await fetch('api/auth/getUsername', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
            },
        });
        const serverResponseData = await serverResponse.json();

        if (serverResponseData.success) {
            isAuthenticated = true;
            username = serverResponseData.data.username;
        } else {
            return window.location.href = '/';
        }
    } catch { } finally {
        $(document).ready(() => {
            // Username and auth buttons elements
            const $authButtonsContainerELM = $('#authButtonsContainer');
            const $navUserContainerELM = $('#navUserContainer');
            const $usernameText = $('#usernameText');

            if (isAuthenticated) {
                $authButtonsContainerELM.css('display', 'none');
                $navUserContainerELM.css('display', 'flex');
                $usernameText.html(username);
            } else {
                $authButtonsContainerELM.css('display', 'flex');
                $navUserContainerELM.css('display', 'none');
            }
        });
    }
})();

And here is my HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>post blog</title>

    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/libs/jquery.min.js">\x3C/script>');</script>

    <script src="./JS/index.js"></script>

    <div>blbalalal</div>
</body>

</html>

Note that the actual HTML code in my source is a bit more complex of-course.

So basically when I go as not authenticated in my browser, I try to access this page.
What happens is, I can see the HTML page for 1 sec then I got redirect back to / path. But I do see the HTML. How can I execute my JS code before the HTML loads?

159 thoughts on “Restrict client from html page using javascript”

  1. You actually make it seem so easy along with your presentation but I to find this
    topic to be actually one thing that I think I would never understand.
    It sort of feels too complicated and very extensive for me.
    I am having a look forward in your next post, I’ll attempt to get the grasp of it!

    Reply
  2. I was recommended this blog by means of my cousin. I am not
    positive whether this put up is written through him as nobody else realize such
    specified about my problem. You’re amazing!
    Thank you!

    Reply
  3. I have been exploring for a little bit for any high quality articles or weblog posts on this sort of area .
    Exploring in Yahoo I ultimately stumbled upon this site.
    Studying this information So i am satisfied to
    exhibit that I have a very good uncanny feeling I came upon exactly what
    I needed. I such a lot indubitably will make sure to don?t fail to
    remember this website and give it a look regularly. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

    Reply
  4. Pingback: ivermectin dosage
  5. Pingback: ivermectin for aml
  6. Pingback: cvs refill online
  7. Awesome site you have here but I was curious about if you knew of any discussion boards that cover the same topics
    discussed in this article? I’d really love to be a part of community where I can get responses
    from other knowledgeable individuals that share the same interest.
    If you have any recommendations, please let me know.

    Appreciate it!

    Reply
  8. That is very interesting, You are a very skilled blogger. I’ve joined your rss feed and
    look ahead to seeking more of your magnificent post.
    Additionally, I’ve shared your site in my social networks

    Reply
  9. I truly love your website.. Great colors & theme. Did you develop
    this website yourself? Please reply back as
    I’m wanting to create my very own blog and would like to find out where you got this from or what the theme is named.
    Thanks!

    Reply
  10. I know this if off topic but I’m looking into starting my own weblog and was
    curious what all is needed to get set up?

    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web smart so I’m not 100% certain. Any tips or advice would be
    greatly appreciated. Thank you

    Reply
  11. I’m amazed, I must say. Rarely do I come across a blog that’s equally educative and engaging, and without a doubt, you have hit the nail on the head.
    The problem is an issue that not enough folks are speaking intelligently about.
    I am very happy that I stumbled across this during my hunt for
    something relating to this.

    Reply
  12. Hi there, i read your blog occasionally and i
    own a similar one and i was just wondering if you get a lot of spam remarks?
    If so how do you protect against it, any plugin or
    anything you can recommend? I get so much lately it’s
    driving me mad so any help is very much appreciated.

    Reply
  13. I do not even know the way I ended up right here, however I
    believed this put up used to be great. I don’t realize who you
    are however definitely you are going to a well-known blogger when you
    are not already. Cheers!

    Reply
  14. My brother suggested I might like this web site. He was totally right.
    This post actually made my day. You can not imagine simply how much time I had spent for this info!
    Thanks!

    Reply
  15. My brother recommended I would possibly like this web site.
    He was totally right. This publish actually made my day.

    You cann’t consider simply how much time I had spent
    for this info! Thank you!

    Reply
  16. Please let me know if you’re looking for a writer for your weblog.
    You have some really great articles and I think I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine.
    Please shoot me an email if interested. Kudos!

    Reply
  17. Pretty nice post. I just stumbled upon your blog and wanted to say that I have
    truly enjoyed browsing your blog posts. In any case I’ll be subscribing to your rss feed and I hope you write again very soon!

    Reply
  18. This design is incredible! You certainly know how to keep a reader entertained.
    Between your wit and your videos, I was
    almost moved to start my own blog (well, almost…HaHa!) Fantastic job.

    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!

    Also visit my page; special

    Reply
  19. I’ll immediately take hold of your rss as I can’t
    to find your e-mail subscription hyperlink or newsletter service.
    Do you have any? Please let me understand in order that I could
    subscribe. Thanks.

    Reply