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
API routes can be dynamic, just like regular Next.js pages
/pages/api/articles/[id].js
Dynamic API Route
User login is not required to access all of the pages.
/pages/unprotected
Unprotected page
next-auth can be used to prevent unauthorized access to protected api methods and protected pages.
$npm install next-auth
Here I used GitHub as an authentication provider.
GitHub Developer Settings
Register a new OAuth application
Note the Client ID and Client Secret
Maintain the Client ID and Client Secret values in an .env file
.env
Add a [...nextauth] api method
/api/auth/[...nextauth].js
Add a 'next-auth/client' Provider to _app.js
_app.js
Provider
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 "Sign In" and "Sign Out" to home page.
/pages/index.js
Sign in
Sign in with GitHub provider
Signed in
authorized
authorized
authorized
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