Home Laravel How to Get Environment Variable in Laravel React JS?

How to Get Environment Variable in Laravel React JS?

by Shahriar Sagor

Today now in this article i will provide you an examples of laravel react js environment variables. Here I would like to share with you a example of how to get env variable in laravel react vite. if you want to know about example of how to get environment variable in react js laravel then i hope you are in the right place. Here i will help you to give an example of laravel react import.meta.env. Alright, let’s start and dive into the steps.

Laravel 9 is added Vite for React JS and Vue JS for front-end development and if we need to add the environment variable in .env file and then need to access .env variable in react js application then here i will help you about how to get environment variable in laravel react js app. So in the laravel added import.meta.env to access all .env variable in js file.

So, let’s statrt and see the below solution with an example:

Add Environment Variable:

Here, I will add “VITE_APP_NAME” environment variable also with title. So let’s add in .env file.

.env

VITE_APP_NAME="Vite React Demo Title"

Access Environment Variable:

So now, i will access “VITE_APP_NAME” environment variable also with title in react js file. Then let’s see the below solution also with an example:

Solution:

import.meta.env.VITE_APP_NAME;

Example Code:

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' });

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like