Prerequisite You should already have a Next.js app created.
Step 1. Install Protocol Auth in your NextjS app:
Step 2. Create a project at https://studio.pxyz.dev


Step 3. Add the environment variables to your .env
file:
Step 4. Project setup (app router)
Add the following code to lib/auth.ts:auth
function. If the user is not authenticated, the function will return null
. If the user is authenticated, the function will return the verified JWT object.
Add an api route to handle the callback from the hosted accounts page. Create a new file called app/api/auth/callback.ts
. Add the following code:
Step 5. Protect pages (app router)
Create a new page in your project that you want to secure. For example, create a new file calledapp/onboard/page.tsx
. Add the following code:
Step 6. Protect api routes (app router)
Create a new file calledapp/api/protected/route.ts
. Add the following code:
Step 7. Protecting server actions
You can also protect server actions by calling theauth
function. For example, if your actions are in lib/actions.ts add the following code:
Step 8. Checking if a user is authenticated in middleware
You can also check if a user is authenticated in middleware. For example, if you want to check if a user is authenticated in a middleware, add the following code:getToken
function. For example:
Step 9. Passing user data to client components
You can easily pass user data to client components from the server. For example, create a new component incomponents/user-button.tsx
. Add the following code: