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.
Execution
The serverless function is a simple JavaScript function that has two arguments:
A request is written as
req.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])
}Code Explanation:
Line 2: The line imports the
axioslibrary to make HTTP requestsLine 5: The
module.exportsstatement exports an asynchronous function as the serverless function to be executed.Line 5: The function is an
asyncfunction that takesreq(request) andres(response) parameters.Line 7: It destructures the
idparameter from thereq.queryobject, which is obtained from the query string of the request URL.Line 10: The function uses
axiosto send an HTTPGETrequest to retrieve a list of users from the JSONPlaceholder API. The retrieved data is stored in theuserListvariable.Line 13–15: The
userListarray is filtered using thefiltermethod to find the user object with anidthat matches the providedid.Line 18: The filtered user object is returned as the JSON response using the
res.jsonmethod, and it is accessed byselectedUser[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