Platform primitives /Functions /

Lambda compatibility for Functions

This page will help you create serverless functions compatible with AWS Lambda. This may be useful if you’re looking to migrate Lambda workflows into Netlify with minimal refactoring required.

Choose your programming language:

# Create function file

To add a serverless function to your project, create a Go file in a dedicated function subdirectory in your functions directory following the instructions below for naming and coding your function. Netlify will access the functions directory during every build, preparing and deploying each supported code file as a function.

The default functions directory is YOUR_BASE_DIRECTORY/netlify/functions. You can optionally configure a custom functions directory.

# Name your function

You must store your function in a subdirectory dedicated to the function. The function’s endpoint name is case-sensitive and determined by the name of its dedicated parent directory.

For example, to create a function with an endpoint name of hello, save the function file in one of the following ways:

  • netlify/functions/hello/hello.go
  • netlify/functions/hello/main.go

These formats would deploy a synchronous function that can be called on the following endpoint: /.netlify/functions/hello. The endpoint is relative to the base URL of your site. Here are some example full endpoint URLs: yoursitename.netlify.app/.netlify/functions/hello for a site using the default Netlify subdomain or www.yourcustomdomain.com/.netlify/functions/hello for a site using a custom domain.

To create a background function, append the function name with -background. For example, to create a background function with an endpoint name of hello-background, save the function file in one of these ways:

  • netlify/functions/hello-background/hello-background.go
  • netlify/functions/hello-background/main.go

These formats would deploy a background function that can be called on the following endpoint: /.netlify/functions/hello-background. The endpoint is relative to the base URL of your site. Here are some example full endpoint URLs: yoursitename.netlify.app/.netlify/functions/hello-background for a site using the default Netlify subdomain or www.yourcustomdomain.com/.netlify/functions/hello-background for a site using a custom domain.

Reserved names for event-driven functions

Certain function names are reserved as triggers initiated by various built-in events on your Netlify site. You can find a list of these function names and how they work on the page about event-driven functions.

# Code your function

This section will help you learn how to write functions. It covers the syntax for both synchronous and background functions.

# Synchronous function format

To create a synchronous function, use the following general syntax in your Go function file. This makes a handler function to receive invocation events:

package main

import (
  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-lambda-go/lambda"
)

func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  // Your server-side functionality
}

func main() {
  // Make the handler available for Remote Procedure Call
  lambda.Start(handler)
}

Here’s a complete example function hello.go:

package main

import (
  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-lambda-go/lambda"
)

func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  return &events.APIGatewayProxyResponse{
    StatusCode:        200,
    Body:              "Hello, World!",
  }, nil
}

func main() {
  lambda.Start(handler)
}
  • This function deploys to an endpoint at /.netlify/functions/hello relative to the base URL of your site.
  • A successful invocation returns the 200 status code and the string, “Hello, World”.

Synchronous functions can return a response object that includes the following information:

return &events.APIGatewayProxyResponse{
  StatusCode: 200,
  Headers:           map[string]string{"Content-Type": "text/plain"},
  MultiValueHeaders: http.Header{"Set-Cookie": {"Ding", "Ping"}},
  Body:       "Hello, World",
  IsBase64Encoded:   false,
}, nil

For more examples to help you learn how to create functions with Go, visit the AWS Lambda for Go repository.

# Access the ClientContext

Netlify can provide extra request information about the context in which the function was called, including certain Identity user information, using a ClientContext parameter.

To access the ClientContext data, do the following:

  • Use a handler definition that includes a Go Context struct.
  • Transform this object into a LambdaContext.

Here is an example:

package main

import (
  "context"

  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-lambda-go/lambda"
  "github.com/aws/aws-lambda-go/lambdacontext"
)

func handler(ctx context.Context, request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  lc, ok := lambdacontext.FromContext(ctx)
  if !ok {
    return &events.APIGatewayProxyResponse{
      StatusCode: 503,
      Body:       "Something went wrong :(",
    }, nil
  }

  cc := lc.ClientContext

  return &events.APIGatewayProxyResponse{
    StatusCode: 200,
    Body:       "Hello, " + cc.Client.AppTitle,
  }, nil
}

func main() {
  lambda.Start(handler)
}

# Background function format

This feature is in Beta and is available on Pro and Enterprise plans.

To create a background function, append the function name with -background. For example, netlify/functions/hello-background/hello-background.go or netlify/functions/hello-background/main.go.

Background function syntax is similar to synchronous function syntax, but you will generally pass the function result to a destination other than the originating client. Like the synchronous function format, a Go file to be deployed as a background function must include a handler function to receive invocation events.

Here’s a simplified example background function that you can use to test that your function runs longer than 30 seconds, count-background.go:

package main

import (
  "log"
  "time"

  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-lambda-go/lambda"
)

func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
  for i := 0; i < 60; i++ {
    log.Println(i)
    time.Sleep(1 * time.Second)
  }
  return nil, nil
}

func main() {
  lambda.Start(handler)
}
  • This function deploys to an endpoint at /.netlify/functions/count-background relative to the base URL of your site.

  • When invoked, the function returns an initial 202 success response.

  • When successfully executed, the function logs numbers 1 through 60.

    Real-time logs only

    The Background Functions beta currently supports only real-time logs. You can’t use the function log date filter to explore log history.

You can explore an extended background function example that demonstrates a more likely use case.

  • This event-triggered background function is called on a new user email and password signup and uses the ctx parameter to access the ClientContext.
  • When the function is executed, it finds and downloads a user’s Gravatar profile image, resizes the image to three different sizes, and saves these images to the site’s repository.
  • For more details, visit the example’s repository README. Note that this extended example doesn’t follow the file name requirements described on this page. That is because rather than using Netlify’s default automatic build workflow, this example uses a custom build with continuous deployment to compile save.go to identity-signup-background.

# Environment variables

Netlify Functions have access to environment variables in the runtime environment. If you have the option to set specific scopes for your environment variables, the scope must include Functions to be available to functions during runtime.

You can also leverage build environment variables to configure how Netlify builds your functions. For example, you can use an environment variable to set the Node.js version.

Learn more about how to set and use environment variables with functions.

# Test locally

To streamline writing and testing your functions on Netlify, run a local development environment with Netlify Dev. This feature of Netlify CLI includes tools for local function development through a simulated Netlify production environment. The netlify dev command starts a framework server if a framework is detected and handles redirects, proxy rules, environment variables, and Netlify Functions.

To simulate Netlify Functions in a standalone server without the full overhead of Netlify Dev, serve functions locally with the netlify functions:serve CLI command.

# Next steps

Push your function source files to your Git provider for continuous deployment where Netlify’s build system automatically detects, builds, and deploys your functions. For more control over the process, learn about other workflows for deploying your functions including custom builds with continuous deployment and manual deploys with the Netlify CLI or API.

Monitor function logs and metrics in the Netlify UI to observe and help troubleshoot your deployed functions.

Netlify function logs are found in the Netlify UI. You can also stream Netlify function logs to the console with the Netlify CLI.