Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

Fire Emoji 70% OFF on our Black Friday Mega Sale with $1.99 eBooks and 100+ Free Courses

How to configure AWS Lambda Function URL with Cross-Origin Resource Sharing

Home » Others » How to configure AWS Lambda Function URL with Cross-Origin Resource Sharing

How to configure AWS Lambda Function URL with Cross-Origin Resource Sharing

Get started learning how to build your first-ever Python Labs Client App, a web application that leverages the power of serverless computing. This creative application is primarily designed to cater to individuals eager to enhance their Python programming skills. By using the flexibility and scalability of AWS Lambda, you’ll be able to create dynamic and interactive web experiences without the hassle of managing infrastructure. This Python Code Playground will be a valuable tool for developers of all levels, providing a hands-on environment to experiment with Python code and learn new concepts. Explore our TechKubo Tutorials for a comprehensive collection of Python code examples and in-depth explanations.

What is Cross-Origin Resource Sharing(CORS)?

CORS (Cross-Origin Resource Sharing) is a security system built into web browsers. It helps control how web pages from one site can access resources from a different site. Typically, browsers block cross-origin access to protect users and security concerns. But sometimes, if you want to share resources with the public, such as APIs, web services, or data across different websites. In such instances, you need to manually enable CORS explicitly.

When using AWS Lambda, you can run your code in response to things like web requests through Lambda Function URLs. These URLs let you access your Lambda function directly over the web without needing API Gateway. However, if you’re trying to access the Lambda function from a different website, the browser will block the request unless CORS is set up correctly.

Setting up CORS is important when you want to make your Lambda services, such as APIs or public resources like Python projects, accessible to other websites. This makes sure the resources can be used safely from different sites while following browser security rules.

In this tutorial, you’ll learn how to enable CORS for a Lambda Function URL so you can securely share public resources, like Python projects, across multiple websites.

Creating Lambda Function

Step 1: Create a new function on AWS Lambda

  • Choose “Author from Scratch

  • Execution Role: “Create a new role with basic Lambda permissions.”

Tutorials dojo strip

  • Under the Advanced Settings:
    • Tick the “Enable function URL”

    • Auth Type: NONE

    • Invoke Mode: BUFFERED

    • Enable :ballot_box_with_check:Configure cross-origin resource sharing (CORS)

    • Once done, you can click “Create function

Step 2: Once you have successfully created a function. We can now modify the code and configuration. 

  • Under the Code Source section, copy and paste the following code snippet:

    import sys
    import io
    import json
    import os
    
    def lambda_handler(event, context):
        
        code =json.loads(event['body'])['code']
        old_stdout = sys.stdout
        new_stdout = io.StringIO()
        sys.stdout = new_stdout
    
        try:
            exec_globals = {}
            exec_locals = {}
            exec(code, exec_globals, exec_locals)
            output = new_stdout.getvalue().strip()
            print('Output:')
            print(output)
            if not output:  # If exec does not print anything, indicate successful execution
                output = 'Tutorials Dojo Code executed successfully.'
        except Exception as e:
            print(e)
            output = str(e)
        finally:
            # Reset standard output
            sys.stdout = old_stdout
    
        return {
            'statusCode': 200,
            'body': json.dumps({
                'output': output
            })
        }
    

Step 3: Once done, click the “Deploy” button to apply the changes. 

 

Creating a Python Labs Client App 

Step 1: Create an HTML file with the following code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Code Playground By Tutorials Dojo</title>
    
<style>
        body {
            font-family: Arial, sans-serif;
        }
        textarea {
            width: 100%;
            height: 200px;
        }
        button {
            padding: 10px 20px;
            margin-top: 10px;
        }
        pre {
            background-color: #f4f4f4;
            padding: 10px;
            border: 1px solid #ddd;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    
<h1>Python Code Playground</h1>

    <textarea id="codeInput" placeholder="Enter your Python code here..."></textarea><br>
    <button onclick="runCode()">Run Code</button>
    
<h2>Output:</h2>

    
<pre id="output"></pre>


    <script>
        async function runCode() {
            const code = document.getElementById('codeInput').value;
            const outputElement = document.getElementById('output');
            outputElement.innerText = 'Executing...';

            try {
                const response = await fetch('https://*********.lambda-url.us-east-1.on.aws', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ code })
                });

                if (!response.ok) {
                    throw new Error(`Tutorials Dojo HTTP error! Status: ${response.status}`);
                }

                const result = await response.json();
                outputElement.innerText = result.output;
            } catch (error) {
                outputElement.innerText = `Error: ${error.message}`;
            }
        }
    </script>
</body>
</html>

Step 2: Copy the Lambda function URL of our newly created Lambda function.

Step 3: Paste the Lambda function URL to your newly created HTML file:

Step 4: Return to the new Lambda function and configure the CORS settings in the ‘Function URL’ section by clicking the ‘Edit’ button.

Step 5: Edit the Function URL:

  • Add the following in the Expose Headers and Allow Headers section
    • content-type

    • access-control-allow-origin

    •  access-control-allow-methods

  • Set the “Allow methods” section to permit ALL HTTP Methods using the  *  wildcard.
  • The Max Age is “Optional”

Step 6: Once done, ensure that the added values are correct. You can now click ‘Save’ to apply the changes.

 

Testing the Python Labs Client App

  • Run your HTML code and check the Network tab in DevTools in your browser.
    • Two domains have status and type.

      • Fetch request 
      • Preflight
Free AWS Courses

    • The preflight request occurs because the browser checks with the server to see if cross-origin requests are allowed, as indicated by the CORS settings in the previous image.

      • We can verify the added values in Expose Headers and Allow headers in the header section.

      • We can also verify that we have used the wildcard – * in the Allow Methods and Allow Origin.

  •  
    • The fetch request is the actual request that retrieves data (usually GET or POST) from the server after the preflight request has confirmed that the CORS settings are correct.

Final Remarks 

After configuring CORS for your Lambda function URL, your Lambda service will now be accessible from different websites without any cross-origin issues. The CORS settings ensure that the browser allows the necessary requests and responses between different origins, letting you securely share your Lambda resources, such as public APIs or Python projects. Please note that CORS is important for protecting users and ensuring that only allowed sites can access your resources. So make sure you always review your settings carefully, especially when it comes to what methods and headers you’re allowing. By using this tutorial guide, you now have a functioning Python Labs Client App that can safely communicate with your Lambda function, handling cross-origin requests as needed. You can always return to the CORS settings to make adjustments if you need to further refine how external websites can interact with your resources.

70% OFF on our Black Friday Mega Sale with $1.99 eBooks and 100+ Free Courses

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

Tutorials Dojo Exam Study Guide eBooks

tutorials dojo study guide eBook

FREE AWS Exam Readiness Digital Courses

FREE AWS, Azure, GCP Practice Test Samplers

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

Follow Us On Linkedin

Recent Posts

Written by: Irene Bonso

Irene Bonso is currently thriving as a Junior Software Engineer at Tutorials Dojo and also an active member of the AWS Community Builder Program. She is focused to gain knowledge and make it accessible to a broader audience through her contributions and insights.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?