0

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:

enter image description here

And if you are:

enter image description here

I am thinking why would you need to secure a route like that?

Am I wrong?

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • 1
    _"why would you need to secure a route"_ - To prevent unauthenticated access to the resources that API route returns. Isn't that what your `api/user` route should be doing anyway? You'd only want to return the user data if that user is logged in. – juliomalves Nov 21 '21 at 12:33
  • I guess my post should _"is it tacky a user could go see some JSON on the screen if they hit that route e.g `api/user`, whether unauthenticated or not?"_ – Antonio Pavicevac-Ortiz Nov 21 '21 at 13:30
  • Depends on your requirements. For that specific route, if it contains sensitive data then I'd avoid exposing it to non-authenticated requests. – juliomalves Nov 21 '21 at 13:36
  • So showing what I have above `{user:null}` for hitting `api/user` while being not authenticated is fine...? – Antonio Pavicevac-Ortiz Nov 21 '21 at 13:39
  • Personally, I'd probably return a `401` response in that scenario. – juliomalves Nov 21 '21 at 14:10

0 Answers0