What are serverless functions in Next.js?

Next.js is an open-source web development React framework. It handles the tools and configuration for React. Next.js has many built-in functionalities like SEO optimization, dynamic routing, and server-side rendering.

Serverless function

A serverless function is a cloud computing model where an application's code is executed in stateless functions that are triggered by specific events or requests. In Node.js there are JavaScript functions that make an HTTP request and send the response. They can be used to handle form submissions, database queries, user authentication, etc.

Location of serverless functions
Location of serverless functions

Execution

The serverless function is a simple JavaScript function that has two arguments:

  1. A request is written as req.

  2. A response is written as res.

Next.js provides inbuilt support allowing you to write serverless functions. You have to create a folder named api, inside the pages directory. The name of the files in this folder is the endpoint of your serverless function. For instance, suppose your folder structure looks like this:

|-- pages
|-- api
|-- getUserData.js

In the folder structure above, getUserData.js is the endpoint to your serverless function. Consider your serverless function as an API, it will take a request object and give a response in return. In your serverless function, you can connect a database and authenticate users, make form submissions, etc.

Writing a serverless function

Let's explore an example where we will use a sample GET API from a JSON placeholder and fetch this data using a serverless function. We will fetch data from the sample API and filter it on the basis of one key, which we will get from query parameters from the request object of our serverless function.

The serverless function should have a filename according to the API. Here, the name is getUserData.js, and a query parameter for our endpoint is id. Using these, we will write our first serverless function.

// import axios library for making HTTP requests
import axios from 'axios';

//export an asynchronous function as a serverless function
module.exports = async(req, res) => {
    // destructure the 'id' parameter from the request query
    const { id } = req.query;

    //make an HTTP GET request to retrieve a list of users from a remote API
    const userList = (await axios.get('https://jsonplaceholder.typicode.com/users')).data;
    
    //filter the userList array to find the user with a matching 'id'
    const selectedUser = userList.filter(item => {
        if(item.id == id) return item // return the user object if the 'id' matches
    });

    // send the selectedUser as a JSON response to the client
    return res.json(selectedUser[0])
}
Output

Code Explanation:

  • Line 2: The line imports the axios library to make HTTP requests

  • Line 5: The module.exports statement exports an asynchronous function as the serverless function to be executed.

  • Line 5: The function is an async function that takes req (request) and res (response) parameters.

  • Line 7: It destructures the id parameter from the req.query object, which is obtained from the query string of the request URL.

  • Line 10: The function uses axios to send an HTTP GET request to retrieve a list of users from the JSONPlaceholder API. The retrieved data is stored in the userList variable.

  • Line 13–15: The userList array is filtered using the filter method to find the user object with an id that matches the provided id.

  • Line 18: The filtered user object is returned as the JSON response using the res.json method, and it is accessed by selectedUser[0].

Execution timeout

Serverless functions have enforced maximum timeout i.e. if the function does not respond to an incoming HTTP request before a timeout is reached, a 504 error status code is returned with the error code FUNCTION-INVOCATION-TIMEOUT. The execution time varies depending on the account plan.

Conclusion

Serverless functions are quite useful when you have to use endpoints without worrying about deploying them on a server. API routing with Next.js serverless functions allows you to build full-stack applications, with backend endpoints, that scale effortlessly.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved