You can easily protect client and server side rendered pages and API routes with NextAuth.js.
You can find working examples of the approaches shown below in the example project.
getToken() both return an
object if a session is valid and
null if a session is invalid or has expired.
If data on a page is fetched using calls to secure API routes - i.e. routes which use
getToken() to access the session - you can use the
useSession React Hook to secure pages.
You can protect server side rendered pages using the
This example assumes you have configured
_app.js to pass the
session prop through so that it's immediately available on page load to
You can protect API routes using the
If you are using JSON Web Tokens you can use the
getToken() helper to access the contents of the JWT without having to handle JWT decryption / verification yourself. This method can only be used server side.
You can use the
getToken() helper function in any application as long as you set the
NEXTAUTH_URL environment variable and the application is able to read the JWT cookie (e.g. is on the same domain).
getToken the same value for
secret as specified in
See the documentation for the JWT option for more information.