Next.js (Part 3)

API routes and next-auth

Get Request

API routes let you create an API endpoint inside a Next.js app.

To create an API endpoint inside a Next.js app add a file (or folder) to the /pages/api directory


articles.js and /pages/api/articles/index.js

Get Request

Dynamic API routes

API routes can be dynamic, just like regular Next.js pages

/pages/api/articles/[id].js

Dynamic API Route

Unprotected pages

User login is not required to access all of the pages.

/pages/unprotected

Unprotected page

next-auth

next-auth can be used to prevent unauthorized access to protected api methods and protected pages.

$npm install next-auth

GitHub Id and GitHub Secret

Here I used GitHub as an authentication provider.

GitHub Developer Settings

Register a new OAuth application

Note the Client ID and Client Secret

.env

Maintain the Client ID and Client Secret values in an .env file

.env

[...nextauth]

Add a [...nextauth] api method

/api/auth/[...nextauth].js

_app.js

Add a 'next-auth/client' Provider to _app.js

_app.js

Provider

Add code to prevent unauthorized access

Ensure that a valid session exists before returning articles or article details (using a REST API call or a web page request)

/pages/api/articles/index.js (updated)

/api/articles is now protected

/pages/api/articles/[id].js (updated)

/api/articles/4 is now protected

/pages/protected.js

page /protected is now protected (server-side)

/pages/protected.js

page /protected is now protected (client-side)

Adding login and logout to home page

Adding "Sign In" and "Sign Out" to home page.

/pages/index.js

Sign in

Sign in with GitHub provider

Signed in

authorized

authorized

authorized

next-auth database (optional)

Specifying a database is optional if you don't need to persist user data or support email sign in. If you don't specify a database then JSON Web Tokens will be enabled for session storage and used to store session data.

To specify a database update the [...nextauth].js file (and a few environment variables).

[...nextauth].js
.env

accounts

users

session (with user id and provider)

pages