How to get env variables in Laravel React Application?

How to get env variables in Laravel React Application?

Hello Buddies, 
This article will provide a complete guide on How to get .env variables in your Laravel React.js application with examples. I will show you examples of Laravel React import.meta.env and process.env. If you are using laravel version 9 then you should use import.meta.env to get env variables and if you are using laravel version below the 9 then you should use process.env to get variables from the .env file in the laravel react.js application. So, let's get started.

Add a new variable in the env file

Let's add a variable in the env file. Should be kept in mind one thing before defining the variable name. If you are using laravel 9 then you should prefix your variable with VITE and if blow the laravel 9 then you should prefix your variable with MIX.

.env (VITE)

VITE_APP_NAME="Coders Vibe"

.env (MIX)

MIX_APP_NAME="Coders Vibe"

Access env variable

Now, you can access the newly defined variable in react.js files. There are two different methods for both VITE and MIX to get variables from the env file in the laravel react application.

VITE

import.meta.env.VITE_APP_NAME;

MIX

process.env.MIX_APP_NAME;

 

Examples

VITE

import './bootstrap';
import '../css/app.css';

import React from 'react';
import { render } from 'react-dom';
import { createInertiaApp } from '@inertiajs/inertia-react';
import { InertiaProgress } from '@inertiajs/progress';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';

const appName = import.meta.env.VITE_APP_NAME;

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        return render(<App {...props} />, el);
    },
});

InertiaProgress.init({ color: '#4B5563' });

MIX

require('./bootstrap');

import React from 'react';
import { render } from 'react-dom';
import { createInertiaApp } from '@inertiajs/inertia-react';
import { InertiaProgress } from '@inertiajs/progress';

const appName = process.env.MIX_APP_NAME;

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}`),
    setup({ el, App, props }) {
        return render(<App {...props} />, el);
    },
});

InertiaProgress.init({ color: '#4B5563' });

I hope it will help you.

Happy Learning :)

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×