Consider the following:
My app uses this route /api/user
to sort of poll for the user in components using a hook via swr to give them access to things in the UI:
import useSWR from 'swr';
import axios from 'axios'
export const fetcher = (url) => axios.get(url).then(response => response.data.user).catch(err => {
if (err.response) {
const error = new Error('An error occurred while fetching the data.')
// error.info = await res.json()
error.status = err.response.status;
error.data = err.response;
console.log(`err.response!`, err.response)
throw error
}
return res.json()
})
export function useUser() {
const { data: user, error, mutate } = useSWR('/api/user', fetcher)
// if data is not defined, the query has not completed
const loading = !user
return {
user,
isLoading: loading === undefined ? 'Loading...' : null,
error,
mutate
}
}
Anyway I came across NextAuth and it provides a way to secure API routes.
So my question is points back to the /api/user
route I mentioned in the beginning of the post.
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
if (req.user != undefined && req.user.isVerified) {
const { id, isVerified } = req.user
res.status(200).send({ user: { id, isVerified } })
} else {
res.status(401).json({
user: null,
})
}
});
export default handler
Right now if type in the browser the route /api/user
and your not logged in you get:
And if you are:
I am thinking why would you need to secure a route like that?
Am I wrong?