Exploring the combination of nextjs and next-auth for authentication using a credential provider has been intriguing. However, I've encountered an issue when attempting to access a protected route while logged in:
[next-auth][error][client_fetch_error]
https://next-auth.js.org/errors#client_fetch_error session FetchError: invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token < in JSON at position 0
at C:\Users\me\workspace\vscode\projects\next-auth-typescript-example\node_modules\node-fetch\lib\index.js:272:32
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
type: 'invalid-json'
}
To replicate this error, follow these steps:
- View the official next-auth example for typescript here: next-auth typescript example
- Proceed with the instructions from the next-auth repository
- Navigate to the file
/pages/api/auth/[...nextauth].ts
- Integrate the credentials provider with the provided code
- Start the server and attempt to log in using any credentials via the credentials provider
- Try accessing the protected route
- Check your console for the encountered error
Below is the code snippet for the credentials provider:
Providers.Credentials({
name: "Ogame Credentials",
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
const user: User = {
id: 1,
name: "J Smith",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba1b8a6a2bfa38baeb3aaa6bba7aee5a8a4a6">[email protected]</a>",
image: "https://google.de",
}
if (user) {
return user
} else {
return null
}
},
}),
This piece of code is also extracted from the examples provided by the next-auth repository.