Frontend Serverless with React and GraphQL

Start at the beginning and work your way through this project. The code for each step as well as the finished project can be found in the Github repository.


21. Add Auth0 Api Functions

Objective: Create Auth0 api functions for logging in and out of the app.

Now that we have an auth0 library, let's create api functions that our frontend can call for authentication related purposes. Next.js api functions take two parameters req and res that allow us to treat these functions much like endpoints in Express.js. The req object is the HTTP request and has all the properties such as the body, headers, query string, and parameters that you'd expect. Similarly, the res object is what we send when we get an HTTP request. This code is pulled from the official Auth0 repository example application for a (Next.js application)[https://github.com/zeit/next.js/tree/master/examples/auth0].

The first method will be the login method. We can call the handleLogin method from the auth0 library that we created in the last video. We wrap a try/catch block around it and respond with an error in the event that something bad occurs.

pages/api/login.ts

import auth0 from '../../utils/auth0';
export default async function login(req, res) {
try {
await auth0.handleLogin(req, res, {});
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}

After logging in, Auth0 will redirect back to a callback function that is available on our api. This function will set a session cookie which we can use on the client to verify that we are logged in and obtain userId and other user specific information.

pages/api/callback.ts

import auth0 from '../../utils/auth0';
export default async function callback(req, res) {
try {
await auth0.handleCallback(req, res, { redirectTo: '/' });
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}

We also create a me route which will return all of the user profile related information based on data that is stored in the session cookie.

pages/api/me.ts

import auth0 from '../../utils/auth0';
export default async function me(req, res) {
try {
await auth0.handleProfile(req, res);
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}

Finally, we will also create a logout route which will clear the session cookie and return the user to the homepage in a non-logged in state.

pages/api/logout.ts

import auth0 from '../../utils/auth0';
export default async function logout(req, res) {
try {
await auth0.handleLogout(req, res);
} catch (error) {
console.error(error);
res.status(error.status || 500).end(error.message);
}
}