Using environment variables in next.config.js allows for successful connection to the database, however, when attempting to use a

Utilizing the serverless-mysql library, I have successfully connected my next app to a remote MySQL DB through an SSH tunnel with the ssh2 library. Although everything is functioning properly, I am looking to enhance the security of my code by removing the environment variables from my next.conf.js file before pushing it to a public repository. My current next.config.js file appears as follows:

module.exports = {
    webpack(config) {
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });

      config.node = {
        fs: 'empty',
        net: 'empty',
        tls: 'empty'
    }
      return config;
    },

    webpackDevMiddleware: config => {
        return config
    },
    env: {
        SSH_PASS:'supersecretpassword',
        SSH_USER:'root',
        SSH_HOST: 'XXX.XXX.XXX.XXX',
        MYSQL_HOST:'127.0.0.1',
        MYSQL_DATABASE:'databasename',
        MYSQL_USERNAME:'username',
        MYSQL_PASSWORD:'dbpassword',
        GOOGLE_CLIENT_ID:'xxxxxx',
        GOOGLE_CLIENT_SECRET:'xxxxxx',
        NEXTAUTH_URL: 'http://localhost:3000/',
    }
  };

To address this concern, I created a .env file in the project root and input the following values:

SSH_PASS="supersecretpassword"
SSH_USER="root"
SSH_HOST="XXX.XXX.XXX.XXX"
MYSQL_HOST="127.0.0.1"
MYSQL_DATABASE="databasename"
MYSQL_USERNAME="username"
MYSQL_PASSWORD="dbpassword"
GOOGLE_CLIENT_ID="xxxxxx"
GOOGLE_CLIENT_SECRET="xxxxxx"
NEXTAUTH_URL=http://localhost:3000/

After making these changes, I encountered an error message when attempting to query the database:

sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client'

I researched the error and attempted various solutions such as ALTER USER and updating the password. However, I suspect that the issue lies elsewhere since the configuration remains consistent and functional with both setups. I even verified this by logging the connection object during the DB connection.

Is there any discernible distinction between loading environment variables from a .env file versus retrieving them from next.config.js?

I appreciate your assistance!

Answer №1

Version 9.3 of next.js introduced the creation of a .env.local file, where variables are automatically added to process.env on the server-side. To access these environment variables in the browser, you need to modify the next.config.js file.

env: {
        SSH_PASS:process.env.SSH_PASS, // .SSH_PASS variable name in .env.local
        ....
        ....
        
    }

If you wish to create your own .env file and utilize the package mentioned here: env-cmd

Make sure to let next.js know in your scripts:

 "dev": "env-cmd -f .env next dev"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

Using PHP Propel ORM to perform a left join on a many-to-many relationship in MySQL

There are two tables I'm working with: one called "meeting" and the other called "attendance". The "attendance" table is a many-to-many relational database structured as follows: Attendance: user_id | meeting_id | invited --------+----------- ...

EJS unable to display template content

I am having an issue with rendering a template that contains the following code block: <% if(type === 'Not Within Specifications'){ %> <% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% ...

% unable to display on tooltip pie chart in highcharts angular js

https://i.stack.imgur.com/Ccd7h.png The % symbol isn't displaying correctly in the highcharts ageData = { chartConfig: { options: { chart: { type: 'pie', width: 275, height: 220, marginTop: 70 ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

Is there a way to eliminate a div and all its contents from the DOM?

As I work on my web application, I am trying to implement a system where error messages can be returned via ajax upon success or failure. The ajax script is functioning correctly in terms of returning errors or successes. However, my challenge lies in com ...

An error occurred while trying to access properties of null during a promise, specifically when trying to read the 'parentNode' property - triggered by calling router.push({})

After updating my dependencies, I encountered an issue every time I clicked on a button to navigate to the next page. The error message Uncaught (in promise) TypeError: Cannot read properties of null (reading 'parentNode') would appear, even thou ...

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

Unleashing the power of Next.js SWR by effortlessly retrieving data from

Encountering a challenge with retrieving data from the cache. Within my dashboard component, data fetching is successful and accessible. const Dashboard = ({ code }) => { const { data, error, mutate } = useSWR(['/api/user', ...

HTML Button without Connection to Javascript

When attempting an HTML integration with GAS, the code provided seems to be generating a blank form upon clicking "Add" instead of functioning as expected: //GLOBALS let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = ss.getLa ...

React has a safeguard in place to restrict the frequency of renders, ensuring that an endless loop

I am currently developing an application and encountering a perplexing error related to the hook I am using for securing pages. Below, I have provided the error message along with the relevant code snippet. Unhandled Runtime Error: Too many re-renders. R ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...

Using Express for Managing Subdomains, Redirects, and Hosting Static Files

I am struggling to configure Express in a specific way and can't seem to get it right. Despite researching on various platforms like SO, I still can't figure it out. Hopefully, by explaining my intentions here, someone can guide me in the right d ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

Design a unique <Link> component within my React shared UI library by utilizing a monorepo approach

As a newcomer to application architecture, I am eager to experiment with building an app using a Monorepo structure. I have a query regarding a Next.js frontend app that utilizes my React-based UI package shared across multiple apps within the same Monore ...

Having issues with ng-view in AngularJs - it's not functioning properly

I am having trouble with the ng-view directive not working. When I implement it, all I see is the "Page" title. Can someone help me diagnose the issue? https://jsfiddle.net/dsgfdyp1/3/ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/b ...

Website created using React without the use of Javascript

Currently, I am considering migrating one of my websites that is built using Python-Flask and Jinja2. The reason behind this decision is primarily due to the limitations of Jinja2's developer experience and the fact that Python is not typed by default ...

Advantages and disadvantages of fetching image paths repeatedly from the database compared to retrieving them from session storage

Currently, I am displaying profile images using session like the following code snippet: <img src="<?php if (isset($_SESSION['userimage'])){ echo $_SESSION['userimage']; }?>" /> What are the advantages and disadvantages of ...