ESP32: Save Wi-Fi Credentials in a Separate File (and Other Sensitive Information)

Learn how to securely store Wi-Fi credentials and other sensitive information in a separate file for your ESP32 projects (also works for other Arduino based projects). This approach eliminates the need to type your credentials in every sketch, while preventing accidental disclosure of personal account details when sharing your code. It also applies to other sensitive data, such as API keys, tokens, and more.

ESP32 Save Wi-Fi Credentials in a Separate File

This tutorial was written by one of our readers, Ron Brinkman, and edited by Sara Santos.

Why Save Your Credentials in a Separate File?

Many projects you create require account names, passwords, tokens, or other sensitive information in order for them to work.

These may be secure if they never leave your desktop, but it can be all too easy to forget and publish or distribute a script file with your personal credentials in it rather than the intended placeholder “REPLACE_WITH_YOUR_PASSWORD”.

You can address this by placing your credentials in a separate file in your libraries folder and including a reference to that file in your sketch initiation. That way, your private credentials will not accidentally escape your desktop and will automatically be included when you compile your sketch.

Additionally, this method removes the need to hardcode credentials or API tokens every time you compile a new sketch that requires them.

You may also like reading: ESP32 Useful Wi-Fi Library Functions (Arduino IDE)

Project Overview

Here is a quick overview of how our approach works:

  • Your private credentials, including account names, passwords, and tokens, are saved in a library file .h, not in your sketch.
  • The library file is #included at the beginning of your sketch.
  • The sketch is modified to reference the #defined name of the private information contained in the library file, keeping the private information out of your sketch.
  • If you subsequently send or distribute your sketch to someone else, you don’t have to take any action to “clean” the file, and you will never have to worry about inadvertently disclosing your personal information because you forgot to edit the file before sending.

Creating/Installing the MyLogin library

We’ll create a library called MyLogin that will hold the credentials. You can give it any other name. Follow the next steps to install a skeleton MyLogin file in your library:

1. Go to the Arduino libraries folder. You can find the path for your Arduino libraries folder, by going to File > Preferences. The path in the Sketchbook location field is where your libraries folder is located.

Arduino IDE libraries folder location

2. Create a folder named MyLogin in your Arduino IDE libraries folder.

    3. Finally, copy the following skeleton code to a file named MyLogin.h in the MyLogin folder and save it.

    Install MyLogin File Arduino Libraries Folder
      /*********
        Created by Ron Brinkman
        Complete instructions at https://RandomNerdTutorials.com/esp32-save-credentials-separate-file/
        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
      *********/
      
      // Keep account names, passwords, tokens, etc. current in this file
      // When visiting another location put their credentials in the "currently in effect" section
      
      // Credentials currently in effect
      #define STASSID               "REPLACE_WITH_YOUR_SSID"                   // WiFi
      #define STAPSK                "REPLACE_WITH_YOUR_PASSWORD"
      
      #define emailSenderAccount    "[email protected]"      // Email
      #define emailSenderPassword   "YOUR_EMAIL_APP_PASSWORD"
      #define emailRecipient        "[email protected]"
      
      #define DuckDNStoken          "YOUR_DUCKDNS_TOKEN"               // DuckDNS
      
      /*********Saved credentials for substitution above when "on the road"
      //Credentials used at home
      #define STASSID               "my_wifi_ssid"
      #define STAPSK                "my_wifi_password"
      #define emailSenderAccount    "[email protected]"
      #define emailSenderPassword   "my_email_app_password"
      #define emailRecipient        "[email protected]"
      #define DuckDNStoken          "my_duckdns_token"
      
      // Credentials used at Mom and Dad's house
      #define STASSID               "parents_wifi_ssid"
      #define STAPSK                "parents_wifi_password"
      
      // Credentials used at wife's Mom and Dad's house
      #define STASSID               "wifes_parents_wifi_ssid"
      #define STAPSK                "wifes_parents_wifi_password"
      
      // Credentials used at our daughter's house
      #define STASSID               "daughter_wifi_ssid"
      #define STAPSK                "daughter_wifi_password"
      
      // Credentials used at our son's house
      #define STASSID               "son_wifi_ssid"
      #define STAPSK                "son_wifi_password"
      
      // Credentials used at our friends Joe and Sally's house
      #define STASSID               "friend_wifi_ssid"
      #define STAPSK                "friend_wifi_password"
      *********/
      

      View raw code

      Customize the MyLogin.h file with your credentials

      Open the skeleton MyLogin.h file in your Arduino IDE installation libraries folder. Follow the next steps to isolate personal account, password, and token information in this private file:

      1) Edit the Credentials currently in effect section. Write your network credentials in the following definition statements, so that applications can connect to your local network.

      // Credentials currently in effect
      #define STASSID               "REPLACE_WITH_YOUR_SSID"                   // WiFi
      #define STAPSK                "REPLACE_WITH_YOUR_PASSWORD"

      2) Continue editing or adding any other credentials your applications use. This may include SMTP email, SMS messaging, Telegram messaging, WhatsApp instant messaging, Duck DNS, NoIP, DynDNS, or other dynamic DNS support, etc.

      For this tutorial, we’ll only be testing the network credentials, but this gives you an idea if you want to add more sensitive information.

      #define emailSenderAccount    "[email protected]"      // Email
      #define emailSenderPassword   "YOUR_EMAIL_APP_PASSWORD"
      #define emailRecipient        "[email protected]"
      
      #define DuckDNStoken          "YOUR_DUCKDNS_TOKEN"               // DuckDNS

      3) Optionally place credentials in the commented-out section of the file so that you don’t need to look them up each time you travel to another location and want to work on your application.

      Start with a copy of your home credentials for the case where the Current credentials are temporarily overwritten while “on the road”.

      // Saved credentials for substitution above when "on the road"
      // Credentials used at home
      #define STASSID               "my_wifi_ssid"
      #define STAPSK                "my_wifi_password"
      #define emailSenderAccount    "[email protected]"
      #define emailSenderPassword   "my_email_app_password"
      #define emailRecipient        "[email protected]"
      #define DuckDNStoken          "my_duckdns_token

      4) Continue customizing with any other family, friend, or business locations’ credentials as needed.

      // Credentials used at Mom and Dad's house
      #define STASSID               "wifes_parents_wifi_ssid"
      #define STAPSK                "wifes_parents_wifi_password"
         .
         .
         .

      Save the file, now containing your private information. It’s ready to be used by your scripts to keep private information out of the scripts.

      Tailoring Your Script Files

      Each script file you want to protect from inadvertent disclosure of your credentials will require two simple edits. Follow the next steps:

      1) Place the following statement in your list of #include files to include the “library” we created previously:

      #include <MyLogin.h>

      2) Find the place in your script file where your account name, password, token, or other credentials would normally be entered. For your WiFi account, it will look something like:

      // Replace with your network credentials
      const char* ssid = "REPLACE_WITH_YOUR_SSID";
      const char* password = "REPLACE_WITH_YOUR_PASSWORD";

      3) Replace the text with the following:

      const char*   ssid     = STASSID;
      const char*   password = STAPSK;

      Don’t fill in your credentials here. They will be incorporated automatically via the MyLogin.h file and #include statement. This will use the values of the STASSID and STAPSK variables defined in the MyLogin.h file.

      4) Continue looking for other places in your script where account names, passwords, or tokens are needed for applications such as SMTP email, SMS messaging, Telegram messaging, WhatsApp instant messaging, Duck DNS, NoIP, DynDNS, or other dynamic DNS support, etc.

      Update these sections of code, similar to the WiFi credentials, to keep personal information out of the script.

      Testing with a Wi-Fi Connection Code

      Let’s test what we’ve learned so far with a simple Wi-Fi example.

      The following code will connect to your local network and print the RRSI (signal strength) once the connection is established.

      /*********
        Created by Ron Brinkman
        Complete instructions at https://RandomNerdTutorials.com/esp32-save-credentials-separate-file/
      *********/
      
      #include <WiFi.h>
      #include <MyLogin.h>
      
      // Replace with your network credentials (STATION)
      const char*   ssid     = STASSID;
      const char*   password = STAPSK;
      
      void initWiFi() {
        WiFi.mode(WIFI_STA);
        WiFi.begin(ssid, password);
        Serial.print("Connecting to WiFi ..");
        while (WiFi.status() != WL_CONNECTED) {
          Serial.print('.');
          delay(1000);
        }
        Serial.println(WiFi.localIP());
      }
      
      void setup() {
        Serial.begin(115200);
        initWiFi();
        Serial.print("RSSI: ");
        Serial.println(WiFi.RSSI());
      }
      
      void loop() {
        // put your main code here, to run repeatedly:
      }
      

      View raw code

      If you’ve successfully created the MyLogin.h file as we explained previously, you don’t need to add any credentials to this code. It will get them through the MyLogin.h file.

      How Does the Code Work?

      The MyLogin.h file, that you have customized per the instructions above, now contains all your personal credentials. It is no longer necessary to enter these credentials anywhere else, because they will be included automatically when the script is compiled.

      The MyLogin.h library file is now securely incorporated into your script when it is included at the beginning of your script, and it contains all your personal credentials.

      #include <MyLogin.h>

      Because your credentials are already incorporated into your script from the included MyLogin.h file, now the credentials are actually incorporated into the script for use in your program.

      const char*   ssid     = STASSID;
      const char*   password = STAPSK;

      If other accounts, passwords or tokens are utilized in subsequent sections of your script, they will be securely incorporated as well if you have customized and tailored them as described in the previous sections.

      Demonstration

      Upload your project to your ESP32 board. It will connect to your local network and print the signal strength.

      ESP32 connects to Wi-Fi and prints the RSSI in the Serial Monitor

      As you can see, there’s no need to hardcode your network credentials in the code because they will be included when you include the MyLogin.h file. You can do this with any other code that uses Wi-Fi credentials, or if you need to save other sensitive information like tokens, APIs, passwords, etc.

      Your private information will be protected from inadvertent disclosure.

      Wrapping Up

      We hope you’ve found this project useful and easy to implement on all of your projects. Enjoy the peace of mind knowing that you can publish or distribute the code for your projects without the fear of “OOPS, I forgot to remove my personal information”.

      Additionally, it avoids having to look for the credentials or API keys every time you need them, so you don’t have to hardcode them.

      We have other tutorials about Wi-Fi that might be useful:

      We hope you’ve found this tutorial useful.

      Special thanks to our reader Ron Brinkman who created and wrote the layout for this tutorial.

      Ron Brinkman is a retired engineer and project manager who desires to keep current in his career technologies. He has utilized RNT and W3Schools materials to great advantage to give back to others by implementing an animated Christmas display in his front yard, and to advocate for better outcomes in his country.

      Learn more about the ESP32 with our resources:



      Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
      Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

      Recommended Resources

      Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

      Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

      Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

      What to Read Next…


      Enjoyed this project? Stay updated by subscribing our newsletter!

      21 thoughts on “ESP32: Save Wi-Fi Credentials in a Separate File (and Other Sensitive Information)”

      1. Thank you Sara, again an interesting and useful article. Can you pls comment how this can be applied in rpi with python?
        Thank you.

        Reply
      2. Great article! I’ve been doing this slightly differently by just adding a .h file into the same folder as my sketch and I add that filename to my .gitignore file. These seems like a much simpler way to do this!

        Reply
        • OK, Blaine, you’re absolutely right.
          I’ve been doing the same thing for years:
          It’s very simple – place a ***.h file with the confidential data somewhere on your computer, preferably with a dummy name such as ‘scratch-dump1.h’.
          Then in the Arduino sketch
          #include ‘drive/path scratch-dump1.h’
          That’s it, folks.
          There’s a German saying: ‘Nothing is so simple that it can’t be complicated.’
          Peter

          Reply
      3. Well, first I thought this would be some separate file at the esp32. This would be quite useful e.g. for selling preprogrammed chips/circuits without preset credentials.
        But as the article may be interesting for a very novice programmer, it demonstrates only a basic usage of include files, which are most common to anyone who had written more then two or three programs. Nearly all modern programming languages use include files and it it a normal habit of breaking a program into different files for code and for constants.

        It should be mentioned in the headline that this is directed to the very beginner to programming.

        Reply
          • Honestly, I as misleaded by the description in the newsletter. I guessed it would be some kind of smart way to store credentials outside of the compiled program located at the esp32, e.g. similar to the “LittleFS” article.
            I am a bit disapointed to find just the standard way of using include files to store some data in the source file system before compilation. -Wether they are called “credentials” or not makes no difference.
            So the only information to mention is that it is also possible to put an include file in a same named folder below the libraries folder. -Which is the standard way libraries do work…
            I find it quite funny to call this a kind of high sophisticated or “expert” usage. So this is the only meaning of my comment about the programming expertise level this article is adressed to.

            Reply
            • @Gunther
              I am having difficulty finding anywhere in this article claiming that this is an expert level technique. It’s just giving you an alternative to storing sensitive information in a single sketch file in case you accidentally share your sketch to someone (likely a single file) and you forget to remove your API key, password etc..

              Thanks for sharing this, Sara, for those who might not know this technique. Though this seems like an obvious way to do this for more seasoned coders, many newbies might not know how to do this. Or, in my case, even thought to do it this way until I was a little more experienced.

              Sara, I’m sure many appreciate your contribution to the community. Looking forward to seeing Gunther’s next tutorial 😉

              Reply
              • Oh my, calm down. Nothing I wrote should offend someone.
                I am reading the RNT tutorials for quite a time and always found interesting and I always read profound and interesting news and ideas.
                I am very thankful for the effort and the work Sara and Rui put into all of them.
                It is just my own feeling that this article does not meet the expectations I had based on the newsletter.
                @Sara: Sorry if it sounded harsh. Take it to the fact that english is not my native language.
                I won’t comment any further.

              • Hi.
                No need to apologize and thank you for sharing your feedback.
                New ideas are always welcome.
                Regards,
                Sara

            • Hi.
              I’m sorry.
              That was not our intention.
              We were just showing one of the many ways you can do so that you don’t have to always have to write your credentials in all sketches.
              I know it may seem basic and simple, but many beginners don’t know how to do it.

              However, yours is a good suggestion. Maybe I’ll try to implement something like that, inside LittleFS in a future tutorial.
              Regards,
              Sara

              Reply
      4. Now, this is what I call a useful tutorial! Very nicely done and written even for the “gurus” out there. I’m sure everyone will benefit from this tutorial. Thank you!

        Reply
      5. Rather than having to change the ‘comment_out’ in the .h file, it might be easier to put the various sections (home, on the road, parents) in an IFDEF structure and when compiling the main ino file just add a line *define HOME” etc…

        Reply
      6. Very nice and interesting Arduino topic and clear explanation.
        But, what about VS Platformio. There is not header file MyLogin.h located in my PC only and in case of publishing whole project, this file could be revealed.

        Reply
        • I am no platformio expert but I would think that can pull in xxxx.h files just as easy, so in my opinion it would work the same, but maybe a true Platformio expert can shine a light on it

          Reply
        • This can be achieved in PlatformIO. VS Code and PlatformIO is all I use now.

          Create a file somewhere outside your project folder like “C:\dev-secrets\wifi_credentials.h”. Added something like this to that file.

          #define MY_SSID "my_ssid"
          #define WIFI_PASS "password"

          Then add this build flag in your platformio.ini.

          build_flags =
          -I C:/dev-secrets

          Now you can include that file in your project.

          #include “wifi_credentials.h”

          Reply

      Leave a Comment

      Download Our Free eBooks and Resources

      Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.