Add TypeScript powered serverless functions to a Netlify project

Jason Lengstorf
InstructorJason Lengstorf
Share this video with your friends

Social Share Links

Send Tweet

Netlify has the power to automatically detect serverless functions in your project and run a functions server with hot reloading for you.

In this lesson, you'll learn how to create serverless functions in your Netlify app using TypeScript

Instructor: [0:00] To add a TypeScript-powered serverless function to any Netlify project, we can start by installing the type definitions for Netlify functions. We're going to do that with npm i @netlify/functions. This is a helper package with several utilities, including an export of types for serverless functions.

[0:18] Next, let's open up our project in VS Code by running code ., that'll take us to the current project. We're going to create a new function. That's going to live in a folder called @netlify/functions. Then, we're going to create helloworld.ts. The ts is so that Netlify knows that it is a TypeScript function.

[0:39] Inside here, let's import Handler from Netlify functions. Then, we're going to export a const called Handler. That is going to be a return type of handler. That's an async function and it's going to return a status code of 200 for OK, and a body of hello TypeScript.

[1:04] Now that we've got that saved, we can run Netlify dev and we'll notice that something changes here. First, it still detected that we're running Vite. It's going to run that Vite server, but it also detected that we have a function, so it starts a function server.

[1:24] All of that runs under the 8888 Port. This allows us to simulate the production environment of running on Netlify. We've got our regular site running here, but we can also go and navigate to that serverless function by going to @netlify/functions/HelloWorld.

[1:43] We can see the result, Hello Typescript. This has live editing. If we change this to say hello world and we reload, we have hello world again. This is a really powerful way to very quickly build TypeScript powered things.

[1:59] You can see that we didn't need to do any kind of compiling. Netlify just picked it up, auto-detected that it was a TypeScript function, and everything runs as expected.