Tips for utilizing various environment files for the "development" and "production" phases in the "aws-nodejs-typescript" template

I have utilized the "aws-nodejs-typescript" template from "serverless" to create a serverless function. My goal is to employ separate .env files for the "dev" and "prod" stages. Is there a way to accomplish this?

Upon deployment, the correct stage is not obtained.

Any advice on how to resolve this issue would be greatly appreciated.

Below is my "serverless.ts" file.

import type { AWS } from '@serverless/typescript';

import {verify} from '@functions/order';


const serverlessConfiguration: AWS = {
  service: 'sample-api-aws',
  frameworkVersion: '3',
  plugins: ['serverless-esbuild', 'serverless-offline'],
  provider: {
    name: 'aws',
    runtime: 'nodejs14.x',
    timeout: 300,
    apiGateway: {
      minimumCompressionSize: 1024,
      shouldStartNameWithService: true,
    },
    environment: (() => {
      const stage = this.provider.getStage();
      console.log(`Environment is : `, stage);
      switch (stage) {
        case 'dev':
          return require('./dev.env').default;
        case 'prod':
          return require('./prod.env').default;
        default:
          return {};
      }
    })(),
  },
  // import the function via paths
  functions: { verify},
  package: { individually: true },
  custom: {
    esbuild: {
      bundle: true,
      minify: false,
      sourcemap: true,
      exclude: ['aws-sdk'],
      target: 'node14',
      define: { 'require.resolve': undefined },
      platform: 'node',
      concurrency: 10,
    },
  },
};

module.exports = serverlessConfiguration;

Here's how I deploy this function in "dev" and in "prod"

Dev

serverless offline start --httpPort 3171 --lambdaPort 3172 --stage dev --noTimeout

Prod

serverless deploy -s prod --aws-profile my_profile 

Note:

I am looking to provide an environment file instead of passing arguments via command-line during deployment.

Answer №1

After doing some research, I was able to discover the solution. I utilized the serverless-dotenv-plugin to achieve this functionality. Check it out at https://github.com/neverendingqs/serverless-dotenv-plugin.

All I needed to do was add the plugin to my serverless.ts file like so:

 plugins: ['serverless-esbuild', 'serverless-offline','serverless-dotenv-plugin']

This plugin automatically retrieves the environment variables from either my .env.dev or .env.prod file depending on the value of --stage in the serverless deploy command.

I hope this information can also assist others in need!

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

Module `coc-tsserver` not found (error ts2307)

https://i.sstatic.net/k1MVW.png Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the s ...

Use the any return type instead of unknown for untyped reducers

Currently in the process of refactoring a large redux state, I am facing an issue with reducers that have not yet been converted to typescript which are returning unknown instead of any. Is there a way to modify the default behavior of ReturnType? import ...

Unable to retrieve this information using $http callback

I am currently working with angular 1.5 and typescript, but I am facing an issue where I cannot access the 'this' property from the callback returned by the $http promise. Whenever I try to access a private method from the callback, 'this&a ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

Duplicate the ng-template using ng-content as the body (make a duplicate of ng-content)

I have been working on creating a feature that allows users to add custom columns to a PrimeNg table. The main reason for developing this feature is to provide users with a default table that already has numerous configuration options pre-set. However, I ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

Guide on showing error message according to personalized validation regulations in Angular 2?

Utilizing a template-driven strategy for constructing forms in Angular 2, I have successfully implemented custom validators that can be utilized within the template. However, I am facing an issue with displaying specific error messages associated with dis ...

Issue with Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

GlobalsService is encountering an issue resolving all parameters: (?)

I am currently working on implementing a service to store globally used information. Initially, the stored data will only include details of the current user. import {Injectable} from '@angular/core'; import {UserService} from "../user/user.serv ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

In search of assistance with implementing Google Maps navigation into an Ionic 2 application

Incorporating external Google Maps navigation with ride distance and time is my goal. I am utilizing a method from phonegap-launch-navigator to achieve this. Here is the code for the method: navigate() { let options: LaunchNavigatorOptions = { s ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

The connection named "Default" could not be located for use with TypeOrm and Express

I am currently facing an issue with my setup involving TypeORM. It seems that Express is being initialized before the connection to the database is established with TypeORM, causing an error message "Connection default not found." Here is a snippet of the ...

The value is not being displayed by ngModel

When working with HTML, I encountered an issue where the ngModel was not displaying even though the selectedValueModel was already assigned. I also tried using [ngValue], which resulted in the value being passed as undefined to my ngModelChange function. ...

Unable to add data to an Array once subscribed to BehaviorSubject

Hello everyone, this is my first time asking a question here. I hope it's clear enough for you to understand :) Let's dive straight into the issue at hand. I have a query regarding a behaviorSubject variable in TypeScript that is not allowing me ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

Nest JS Guards - Employ either of two approaches

I have implemented two different JWT based strategies in my application: The first strategy involves single sign-on for organization members, where an external provider generates a JWT. The second strategy is for email/password authenticated external user ...

Retrieve the API output and save the information into an array

I am struggling with calling an API in my Angular application and extracting specific data from the JSON response to populate an array. Although I am able to retrieve the response, I am having trouble isolating a particular field and storing it in an array ...