Expand my Community achievements bar.

AEM SPA - determine .env file at build time

Avatar

Level 2
The issue is related to the SPA React package at build time. We used the aem-project-archetype as the starting point. It included a ".env" file in the ui.frontend folder to specify the environment variables for the React app. The ".env" file is used to inject the environment variables to the React app when the project is built (mvn clean install -PautoInstallPackage --> npm run build).
 
I have searched this forum and found that some people pull the runmode via some hidden html but this is not a desirable approach as the .env used in the project archetype injects the variables within the app at build time but not runtime.
 
Are we able to obtain the runmode osgi configuration at project build time?  If this is not feasible, what is the recommended way to setup environment variables for the frontend app in an AEM SPA project?
1 Reply

Avatar

Community Advisor

@phychem_ad  You can expose the environmental variable from AEM and based on that you can handle the requests in ui,frontend module.

Something similar to below:
@Component(
service = { Servlet.class },
property = {
Constants.SERVICE_DESCRIPTION + "=Environment Variables Servlet",
"sling.servlet.paths=/bin/environment/variables",
"sling.servlet.methods=GET"
}
)
public class EnvironmentVariablesServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().write("{ \"apiUrl\": \"" + System.getenv("API_URL") + "\" }");
}
}