Dmitry
Dmitry

Reputation: 4373

pass environment variable from django to react app

I would like to pass a variable from django to react app. I know I can do it by passing window object from html page but I would like to know if its possible to do it using environment variable. I came across this link How can I pass a variable from 'outside' to a react app? which mentions using .env file. Please advise on how it can be used with Django/Python setup.

Upvotes: 6

Views: 2817

Answers (1)

trixn
trixn

Reputation: 16354

Just render it into a script tag in your template:

<script type="text/javascript">
    var globallyVisibleVar = {myVar}
</script>

But you will have to make sure, that the variable is JSON serialized. You could either write a template tag or JSON serialize it before passing it to the template context. Also make sure to use var and not const or let because they are block scoped and will not be globally visible in your react app.

As the documentation of create-react-app says:

The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like described here. Alternatively you can rebuild the app on the server anytime you change them.

Since you do not want to rebiuld your whole JavaScript on every request you can't use that to share dynamic data between your server application (Django) and your client application (react).

So if you follow the link you will read this:

Injecting Data from the Server into the Page

Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example:

<!doctype html>
<html lang="en">
    <head>
    <script>
        window.SERVER_DATA = __SERVER_DATA__;
    </script>

Then, on the server, you can replace __SERVER_DATA__ with a JSON of real data right before sending the response. The client code can then read window.SERVER_DATA to use it. Make sure to sanitize the JSON before sending it to the client as it makes your app vulnerable to XSS attacks.

Upvotes: 5

Related Questions