[▲ Vercel Community](/) · [Categories](/categories) · [Latest](/latest) · [Top](/top) · [Live](/live)

[Help](/c/help/9)

# Middleware code to access country_code coming from cloudflare

177 views · 0 likes · 5 posts


EdYoda (@edyoda1-gmailcom) · 2025-03-07

Below is my middleware code where I am trying to log to firebase, it doesn't seem to be getting called.  Folks, any inputs?

```ts
import { NextResponse } from 'next/server';
import axios from 'axios';
import Constants from '@/utilities/Constants'

export async function middleware(req) {
    // Get country code from Cloudflare header (or default to 'Unknown')
    const countryCode = req.headers.get('cf-ipcountry') || 'Unknown';

    // Create a new response and attach the country code
    const response = NextResponse.next();
    response.headers.set('X-Country-Code', countryCode);

    console.log("Middleware Detected Country:", countryCode); // Won't log in terminal, check browser console or network tab
    try {
        const data = { countryCode: countryCode, url: "middleware", date: new Date().toString() };
        const response = await axios.post(Constants.FIREBASE_ERROR_LOGS_URL, data);
        console.log('Firebase log successful-middleware:', response.data);
    } catch (error) {
        console.error('Error logging to Firebase:', error);
    }


    return response;
}

// Apply middleware to all routes
export const config = {
    matcher: '/:path*',
};
```


Anshuman Bhardwaj (@anshumanb) · 2025-03-07

Hi @edyoda1-gmailcom, welcome to the Vercel Community!

Can you share the logs from Vercel where you make the requests? Which path are you making the requests to?


EdYoda (@edyoda1-gmailcom) · 2025-03-07

Hello @anshumanb ,

I don't this getting logged in vercel. Have minimal code.  I am using nextjs 14 & this code is in the level of next.config.mjs

```
import { NextResponse } from 'next/server';

export function middleware(request) {
    console.log("Middleware running for:", request.nextUrl.pathname);
    return NextResponse.next();
}

// Apply middleware to all routes
export const config = {
    matcher: '/:path*', // Middleware runs for all routes
};
```


Anshuman Bhardwaj (@anshumanb) · 2025-03-07

Hi @edyoda1-gmailcom, thanks for sharing additional context. Are you using the `src/` structure? If so, the `middleware.ts` should be inside the `src` but outside the `app/`.

Can you also check if you get a middleware created as part of the deployment summary, as follows:

![Deployment summary](upload://l9iGT4Yx6dhr4FVoWOIF9oH5tig.png)


system (@system) · 2026-01-20

Hey @edyoda1-gmailcom! 👋

Just checking in on this thread. If you're still experiencing issues or have additional details to share, please let us know! We're here to help.