'Is it possible to use API Routes as Proxy to my existing RoR Backend

Every time NextJs request for an api, it will come first to api routes before it redirected to my RoR backend service.

I use this to encrypt my access token to session NextJS using iron-session once I get the data from backend.

## src/pages/api/login.ts
const loginRoute = async (req: NextApiRequest, res: NextApiResponse) => {
  const response = await fetch(`backend-service/authorizations.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: req.body.username,
      password: req.body.password
    })
  })
    .then((res) => {
      if (!res.ok) {
        return res.text().then((text) => {
          throw new Error(text)
        })
      }
      return res
    })
    .then((res) => res.json())
    .catch((err) => {
      res.status(401).json({ message: err })
    })

  if (response) {
    req.session.user = response
    await req.session.save()
    res.json(response)
  }
}
export default withSessionRoute(loginRoute)

Is this a valid use case for API Routes in NextJS?

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source