How can I run Javascript on Django without exposing static files?

Viewed 59

On my Django site, I used Stripe to integrate payments in a .js file.

I noticed that this file appears under Sources in the developer tools when you "Inspect Element" on any browser. Anyone can access this file (scary).

How can I restructure my file organization so that apple-pay.js is not public facing?

home.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
    // Scripts for CSS and Stripe Pay
</head>
<body>
    <section>
        
       <div id="payment-request-button" data-amount="{{event.price}}" data-label=". 
          {{event.public_name}}">
                    <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. -->
       </div>
       <div id="messages" role="alert"></div>

    </section>

</body>
</html>

apple-pay.js

document.addEventListener('DOMContentLoaded', async () => { 
    const stripe = Stripe('pk_mykeyishere'); //need to protect this information and the other functions from bad actors

    ///functions I run here
    
});

My file structure:

├── Procfile
├── README.md
├── db.sqlite3
├── interface
│   ├── migrations
│   ├── models.py
│   ├── static
│   │   ├── apple-developer-merchantid-domain-association
│   │   └── interface
│   │       ├── apple-pay.js <------------------
│   │       ├── CSS/other JS files
│   ├── templates
│   │   └── interface
│   │       ├── home.html <-------------------
│   ├── urls.py
│   └── views.py
├── manage.py
└── AppName
    ├── settings.py
    ├── urls.py
    └── wsgi.py
1 Answers

You cannot hide JavaScript code from browser users, you can only minify and/or obscure it to make it harder for people to read and understand.

Stripe integration does not require you to put sensitive data into any JavaScript file. You should use that data on the server-side.

Related