Learning Next.js: Part 5: Serverless API

Learning Next.js

Next.js is a JavaScript framework based on React for rapidly developing web sites and applications.

Serverless API

Along with its Pages and Dynamic Routing functionality, Next.js also provides a structure for developing a “serverless” API.

More generally, a “serverless API” loosely describes a development pattern where the front-end and back-end development happens as part of the same “server” structure. For Next.js, this means that the software serving the front-end (Next) will also be the same serving the back-end (Next).

The “api” folder

Creating an “api” folder inside of the existing “pages” folder tells Next.js to create an API structure. For each file within the folder, like with Pages, Next.js will assume it is its own route.

The following structure —


— can be accessed through the route “/api/post”.

HTTP Server-like Functionality

Files within the “api” folder are assumed to be server-like functionality and inherit HTTP Server functions.

Like with Pages, files do not need to import other functionality. They will be passed NextApiRequest (extending http.IncomingMessage) and NextApiResponse (extending http.ServerResponse) to any exported functions.

export default (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    res.statusCode = 200;
    res.end(JSON.stringify({ name: 'Hi!' }));

To help with common tasks, Next.js also supplies chainable functions to condense three line of codes into a single, chained function call to accomplish the same task.

export default (req, res) => {
    res.status(200).json({ name: 'Hi!' })

Writing Front-End Functionality

Within the serverless pattern, front-end components can access data through using fetch() and other AJAX-like functionality. Like with Pages, routes are assumed to proceed from the root outward. The existing “/api/post” route, then, can be called and its JSON data retrieved, parsed, and used.

import React from "react";

class Index extends React.Component {

  constructor(props) {

    this.state = {
      greeting: ""


  componentDidMount() {

    .then((res) => res.json())
    .then((data) => {
      this.setState({greeting: data.name});


  render() {


        Server says "{this.state.greeting}"




export default Index;