Intermediate 25 min

Configuration with Environment Variables

Environment variables let you change settings without editing code. Useful for secrets, API keys, and configuration.

Setting Environment Variables in Lambda

  1. Go to your Lambda function
  2. Scroll to “Configuration” tab
  3. Click “Environment variables”
  4. Click “Edit”
  5. Add variables:
    • Key: MESSAGE
    • Value: Hello from Lambda
  6. Click “Save”

Using Environment Variables in Code

Update your handler to use the variable:

exports.handler = async (event) => {
  const message = process.env.MESSAGE || 'Default message';
  
  if (event.path === '/health' && event.httpMethod === 'GET') {
    return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        status: 'ok',
        message: message,
        timestamp: new Date().toISOString()
      })
    };
  }
  
  // ... rest of your code
};

Access: Use process.env.VARIABLE_NAME just like in Node.js.

Why use them:

  • Keep secrets out of code
  • Different settings for dev/prod
  • Easy to change without redeploying code

Common Environment Variables

Configuration:

  • NODE_ENV - development or production
  • API_VERSION - Version of your API
  • LOG_LEVEL - debug, info, error

Secrets (use AWS Secrets Manager for real secrets):

  • DATABASE_URL - Database connection string
  • API_KEY - External API key
  • JWT_SECRET - Secret for tokens

For this tutorial: We’ll just use MESSAGE as an example.

Logging and CloudWatch

Lambda automatically sends logs to CloudWatch. Every console.log() appears there.

Adding Logs to Your Code

exports.handler = async (event) => {
  console.log('Received event:', JSON.stringify(event, null, 2));
  
  const path = event.path || event.requestContext?.path || '';
  const method = event.httpMethod || event.requestContext?.httpMethod || 'GET';
  
  console.log(`Processing ${method} ${path}`);
  
  // ... your code ...
  
  console.log('Returning response:', response);
  return response;
};

Viewing Logs in CloudWatch

  1. Go to AWS Console → CloudWatch
  2. Click “Log groups”
  3. Find /aws/lambda/notes-api (your function name)
  4. Click on it
  5. Click on a log stream (each invocation creates a stream)
  6. See your console.log() output

Log format:

START RequestId: abc-123
2025-12-02T10:00:00.000Z	abc-123	Received event: {...}
2025-12-02T10:00:00.100Z	abc-123	Processing GET /notes
2025-12-02T10:00:00.200Z	abc-123	Returning response: {...}
END RequestId: abc-123

Understanding Log Levels

Use different log levels for different information:

// Debug info (verbose)
console.log('DEBUG: Full event:', event);

// Info (normal flow)
console.log('INFO: Processing request');

// Warnings (something unusual)
console.warn('WARN: Missing optional field');

// Errors (something wrong)
console.error('ERROR: Failed to process:', error);

CloudWatch shows all of these. In production, you might filter by level.

Common Errors and How to Debug

Error 1: “Task timed out”

What it means: Your function took too long to run.

Default timeout: 3 seconds (you can increase it).

How to fix:

  1. Go to Lambda → Configuration → General configuration
  2. Click “Edit”
  3. Increase “Timeout” (max 15 minutes)
  4. Click “Save”

Why it happens:

  • Code is slow (loops, network calls)
  • Waiting for external services
  • Processing large data

Debug:

  • Check CloudWatch logs for where it stops
  • Add timing logs: console.log('Step 1:', Date.now())

Error 2: “Cannot find module”

What it means: Lambda can’t find a required file or package.

How to fix:

  • Make sure all files are in the zip
  • If using node_modules, include them in the zip
  • Check file paths are correct

Debug:

  • Check the zip file contents
  • Verify handler name matches file name

Error 3: “JSON parse error”

What it means: event.body is not valid JSON.

How to fix:

let body;
try {
  body = typeof event.body === 'string' 
    ? JSON.parse(event.body) 
    : event.body;
} catch (e) {
  return {
    statusCode: 400,
    body: JSON.stringify({ error: 'Invalid JSON' })
  };
}

Debug:

  • Log event.body to see what you received
  • Check Content-Type header is application/json

Error 4: “Handler not found”

What it means: Handler name doesn’t match your code.

How to fix:

  • Check handler setting in Lambda
  • Format: filename.functionName
  • File: lambda-handler.js, Function: handlerlambda-handler.handler

Error 5: “Internal server error” (500)

What it means: Something crashed in your code.

How to fix:

  • Check CloudWatch logs for the error message
  • Look for stack traces
  • Add try-catch blocks:
exports.handler = async (event) => {
  try {
    // your code
  } catch (error) {
    console.error('Error:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Internal server error' })
    };
  }
};

What Happens If… Scenarios

What happens if JSON.parse fails?

Scenario: Client sends invalid JSON.

Result: Error in your code, 500 response.

Solution: Wrap in try-catch, return 400 with helpful message.

What happens if a variable is undefined?

Scenario: You access req.body.text but body is empty.

Result: undefined, might cause errors later.

Solution: Validate input:

if (!text) {
  return {
    statusCode: 400,
    body: JSON.stringify({ error: 'text is required' })
  };
}

What happens if Lambda runs out of memory?

Scenario: Your function uses more memory than allocated.

Result: Lambda kills the function, you get an error.

Solution: Increase memory in Lambda settings (also increases CPU).

Lambda Configuration Settings

Memory

Default: 128 MB

Range: 128 MB to 10 GB

Why it matters: More memory = more CPU. If your code is slow, try increasing memory.

How to change:

  1. Lambda → Configuration → General configuration
  2. Click “Edit”
  3. Adjust “Memory”
  4. Click “Save”

Timeout

Default: 3 seconds

Range: 1 second to 15 minutes

Why it matters: API Gateway times out at 30 seconds, so Lambda should finish faster.

How to change: Same as memory, but adjust “Timeout”

Environment Variables

Limit: 4 KB total

Best practice: Use AWS Secrets Manager for large secrets.

Test Your Knowledge

Key Takeaways

Before moving on:

  1. Environment variables - Use process.env.VARIABLE_NAME to access them
  2. CloudWatch logs - All console.log() goes there automatically
  3. Common errors - Timeout, module not found, JSON parse errors
  4. Debugging - Check logs, add try-catch, validate input
  5. Configuration - Memory and timeout affect performance

What’s Next?

In the next page, we’ll talk about costs and cleanup. Important for responsible cloud use.