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 —


/pages
/api
/api/post.js

— 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) {
    super(props);

    this.state = {
      greeting: ""
    };

  }

  componentDidMount() {

    fetch("/api/post")
    .then((res) => res.json())
    .then((data) => {
      this.setState({greeting: data.name});
    });

  }

  render() {

    return(

      <div>
        Server says "{this.state.greeting}"
      </div>

    );

  }

}

export default Index;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.