Build serverless functions with TypeScript

You can create Netlify Functions using TypeScript. Our build system will automatically detect .ts files in your site’s functions directory, bundle them with esbuild, and deploy them along with the rest of your site. Serverless functions built with TypeScript have the same naming, directory location, and runtime considerations as Netlify Functions built with JavaScript.

# Project preparation

  • Before creating a TypeScript function, add the @netlify/functions module to your project to import typings for TypeScript:

    npm install @netlify/functions
    
  • Set up tsconfig.json. We recommend that you enable the properties esModuleInterop and isolatedModules in your TypeScript configuration file for better compatibility. During the build process, Netlify automatically loads any tsconfig.json configuration files found in your functions directory, the repository root directory, or the base directory, if set.

# Function format

Next, create a TypeScript function in your functions directory. When naming the file, note the naming considerations in our build with JavaScript docs.

Here’s an example:

import { Handler } from "@netlify/functions";

const handler: Handler = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello World" }),
  };
};

export { handler };

For serverless functions built in TypeScript, you have to import a type before declaring the function. When you use the Handler type, the event and context arguments and the response are typed accordingly. Alternatively, you can import the types HandlerEvent, HandlerContext, and HandlerResponse separately and use them to construct a handler function.

For more information about the event and context parameters, refer to our build with JavaScript docs. Netlify Functions built in TypeScript can follow either synchronous function format or background function format.

# Type check

Because Netlify’s build system doesn’t perform type checking, we recommend one of these options instead:

  • Type check during local development using a modern code editor.
  • Use the official TypeScript compiler, running tsc --noEmit locally before committing the files.

# TypeScript and JavaScript together

If you include JavaScript and TypeScript functions with the same name, for example, my-function.js and my-function.ts, the JavaScript function is deployed while the TypeScript function is ignored. This allows you to handle TypeScript compilation in a build command, if preferred. Netlify then bundles and deploys the resulting JavaScript function.

Meanwhile, if you’re using a Netlify configuration file to configure custom [functions] settings, note that the node_bundler value for TypeScript functions always overrides to esbuild.