Carl Willimott - Tech Blog: Using the correct amplify config in expo builds

Using the correct amplify config in expo builds

October 24, 2022

3 min read

Back

If the following 3 bullet points relate to you, then this could be a simple solution for ensuring you are able to use the correct configuration for your application.

  • You are building a React Native app
  • You are using Expo
  • You are using AWS Amplify

Preparing your aws-exports.json file

After using Amplify for a while you should be well versed with the aws-exports.json config file which can be found locally in your codebase. Because of the sensitivity of the content within the file, this is not something you want to commit, and is also different depending on which environment you are currently working with.

If you run the following command you will receive a base64 encoded string of the file which you can then copy-and-paste into Expo as an app secret.

$ base64 aws-exports.js

I typically have 2 environments - one for production and the other for development. For this reason I create both an AWS_EXPORTS and an AWS_EXPORTS_DEVELOP secret in Expo.

Assuming you completed this step correctly you will be able to reference them as environment variables in the next step.

Adding a pre-install script

The following script should be placed in a file called pre-install.js (or something else if you prefer). As you can see in the script we effectively load the correct base64 encoded string and then write it to a file in the build so that it can be referenced.

const fs = require("fs");

const buildProfile = process.env.EAS_BUILD_PROFILE;
const configProd = process.env.AWS_EXPORTS;
const configDevelop = process.env.AWS_EXPORTS_DEVELOP;

const config = buildProfile === "production" ? configProd : configDevelop;

const decoded = Buffer.from(config, "base64").toString();

fs.writeFileSync("./src/aws-exports.js", decoded);

Please note - in order to access the EAS_BUILD_PROFILE variable, you will need to ensure you set this flag when actually starting the build with the expo-cli. For example, something like this.

$ eas build --platform all --profile production

In the above example we are building for all platforms and setting the profile to production.

Trigger your script

The final step is to add the eas-build-pre-install script in your package.json file. This is a hook which will automatically get called by Expo during the build process, and in effect kicks the whole thing off.

{
  "scripts": {
    "eas-build-pre-install": "node scripts/pre-install.js"
  }
}

Conclusion

Assuming you have done all the previous steps correctly you should be able to easily switch between different environments in your expo builds!

Useful links