Skip to main content

Using the API Router

tip

This doc assumes you're storing your pages/styles/etc. in a directory called src, and you have the baseUrl option set to src in your tsconfig.json for importing modules from the root.

The API Router is a node middleware that handles all of the Faust.js related API routes for you.

Currently, there are two API routes that are handled by the API Router:

  • auth/token: A route to handle a request for an authentication token
  • auth/logout: A route to handle a request to logout

With the API router, we have the ability to add more routes as needed, without requiring any changes from the user.

Usage

By default, the API router is expected to be mounted at /api/faust. This is the base path that the API router will use to handle all of the routes (i.e. /api/faust/auth/token).

To configure this in Next.js, you would create a faust directory in your api routes directory, with a catch-all route file named [[...route]].ts. The complete file path would then be:

src/pages/api/faust/[[...route]].ts

Now, add the following content to your newly created [[...route]].ts file:

src/pages/api/faust/[[...route]].ts
import 'faust.config';
import { apiRouter } from '@faustjs/core/api';

export default apiRouter;

Your API Router is now setup and ready to handle all Faust.js related API routes from /api/faust/*.

Modifying the API Router Base Path

You may find a need to modify the base path of the API Router. For these use cases, the apiBasePath config option can be used.

Say for example, you want to mount the API router at /api/headless. You would first specify this base path in your faust.config.ts file:

faust.config.js
import { config as coreConfig } from '@faustjs/core';

if (!process.env.NEXT_PUBLIC_WORDPRESS_URL) {
console.error(
'You must provide a NEXT_PUBLIC_WORDPRESS_URL environment variable, did you forget to load your .env.local file?',
);
}

/**
* @type {import("@faustjs/core").Config}
*/
export default coreConfig({
wpUrl: process.env.NEXT_PUBLIC_WORDPRESS_URL,
apiClientSecret: process.env.FAUSTWP_SECRET_KEY,
apiBasePath: '/api/headless',
});

Then, you would replicate this path in your Next.js API routes directory, by creating a headless directory, and adding a [[...route]].ts file to it. The complete file path would then be:

src/pages/api/headless/[[...route]].ts

Finally, the content of src/pages/api/headless/[[...route]].ts would be:

src/pages/api/headless/[[...route]].ts
import 'faust.config';
import { apiRouter } from '@faustjs/core/api';

export default apiRouter;

Your API Router will now be handling all Faust.js related API routes from /api/headless/*.