How to protect NextJS API routes from other browsers/servers

So you have any API routes that you don't want anything to access other than the UI (main website) itself, and you don't want to keep writing if statements on every single one of your API routes. What's the solution?

Writing middleware

Let's create a folder called middleware in our NextJS project and under it create a file called protectAPI.js.

const protectAPI = (handler) => {
    return async (req, res) => {
        if(new URL(req.headers.referer).origin !== 'http://yourdomain.com') {
            return res.status(403).json({success: false, message: `Forbidden`})
        }
        return handler(req, res)
    }
}

export default protectAPI;

Now let's see what's going on here. First of course we define the function protectAPI. We return an asynchronous function which has our req and res.

Now we check the domain that's sending a request with req.headers.referer and seeing if it's not our domain name, return the 403 code and a Forbidden message.

Using this middleware

So we have an API file which is under /api/hello.js. How do we protect it?

import protectAPI from '../../middleware/protectAPI';

const handler = (req, res) => {
    return res.status(200).json({message: 'Hello world!'})
}

export default protectAPI(handler);

We import the protectAPI function that we wrote before, and then write our API function which in this case is called handler.

At the end we export it by wrapping the handler function with our protectAPI function.

Conclusion

And there you go! Now no domain/browser outside of your own domain can make any requests to /api/hello.

I hope this helped you 😀

16