Skip to content

Starting to work with Lambda @ Edge - code does not refresh

0

I am trying to follow some simple tutorials to understand how to use Lambda @ Edge with Cloudfront to solve a problem.

I am having trouble getting started because debugging the code is very hard as it does not refresh.

For example, I created a very simple helloworld type thing:

export const handler = async (event) => {
  
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

Which runs fine given a test. However, if I now add a new line or change the code - e.g. change the body string to say New Code!, it still returns Hello from Lambda!

The Last Modified property is also showing several minutes ago, not keeping up with the changes I am making. Is there something I need to do in order for my code changes to be reflected in new tests?

Edit: do I need to Deploy the code in the Code Editor for my changes to be reflected?

2 Answers
2

The behavior you're experiencing is expected when working with Lambda@Edge functions. There are a few important points to understand about how Lambda@Edge works and how to ensure your code changes are reflected:

  1. Version Management: When you associate a Lambda@Edge function with a CloudFront distribution, you're actually associating a specific version of the function, not the $LATEST version. This means that simply updating the code in the Lambda console won't automatically update the version being used by CloudFront.

  2. Publishing New Versions: To see your changes take effect, you need to publish a new version of your Lambda function after making changes. This creates a new, immutable version of your function.

  3. Updating CloudFront: After publishing a new version, you need to update your CloudFront distribution to use this new version. This typically involves editing the behavior in your CloudFront distribution and selecting the new function version.

  4. Propagation Time: Changes to CloudFront distributions can take some time to propagate globally, usually around 5-10 minutes, but it can sometimes take longer.

To get your code changes reflected:

  1. Make your changes in the Lambda console.
  2. Publish a new version of your Lambda function.
  3. Update your CloudFront distribution to use the new version.
  4. Wait for the changes to propagate.

Remember, Lambda@Edge functions are replicated globally when associated with a CloudFront distribution, which is why there's an additional step compared to regular Lambda functions. This process ensures that your edge functions remain consistent and performant across all edge locations.

For easier development and debugging, consider setting up a local testing environment that mimics the Lambda@Edge event structure. This can help you iterate more quickly before deploying changes to your production environment.

Sources
Get started with Lambda@Edge functions (console) - Amazon CloudFront
Customize at the edge with Lambda@Edge - Amazon CloudFront

answered a year ago

EXPERT

reviewed a year ago

  • What is the recommended way to setup a local testing environment that mimics the Lambda@Edge event structure?

1
Accepted Answer

yes you need to Deploy your changes in the Code Editor for them to take effect. Below are the steps which you can follow :

  • Make your code changes in the editor
  • Click the "Deploy" button to save and apply your changes
  • After deployment, run your tests to see the new behavior

Further, sharing one of the ways to setup the local testing environment for Lambda@Edge :

  1. Create a Mock Event Helper.
// mockEventGenerator.js
const generateViewerRequestEvent = () => ({
  Records: [{
    cf: {
      config: {
        distributionDomainName: 'test.cloudfront.net',
        distributionId: 'EDFDVBD6EXAMPLE',
        eventType: 'viewer-request',
        requestId: 'MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkfUdSQ=='
      },
      request: {
        clientIp: '2001:cdba::3257:9652',
        headers: {
          'host': [{ key: 'Host', value: 'test.cloudfront.net' }],
          'user-agent': [{ key: 'User-Agent', value: 'Test Agent' }]
        },
        method: 'GET',
        uri: '/test',
        querystring: 'test=123'
      }
    }
  }]
});

module.exports = {
  generateViewerRequestEvent
};
  1. Setup Local Test Environment :
// local-test.js
const { handler } = require('./your-lambda-function');
const { generateViewerRequestEvent } = require('./mockEventGenerator');

async function runLocalTest() {
  const event = generateViewerRequestEvent();
  try {
    const result = await handler(event);
    console.log('Result:', JSON.stringify(result, null, 2));
  } catch (error) {
    console.error('Error:', error);
  }
}

runLocalTest();
  1. Use Jest for Unit Testing:
// your-lambda-function.test.js
const { handler } = require('./your-lambda-function');
const { generateViewerRequestEvent } = require('./mockEventGenerator');

describe('Lambda@Edge Function Tests', () => {
  test('handles viewer request correctly', async () => {
    const event = generateViewerRequestEvent();
    const response = await handler(event);
    expect(response).toBeDefined();
    // Add more specific assertions
  });
});
  1. Create a Package.json with respective dependency.
{
  "scripts": {
    "test": "jest",
    "local": "node local-test.js"
  },
  "devDependencies": {
    "jest": "^29.0.0"
  }
}
AWS

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.