skip to Main Content

I am currently facing an issue where I always receive a port number in my Next.js requests. I am using an Express server in conjunction with Next.js. The problem arises when I attempt to redirect from uppercase to lowercase for certain scenarios within my application. Since the URL contains a port number, the redirection leads me from ‘https://www.cyx.com/test/TEST’ to ‘https://www.cyx.com:3000/test/TEST’.

How can I obtain the correct value for the pathname in Next.js middleware, without including the port number in the URL?

2

Answers


  1. Chosen as BEST ANSWER

    When using a custom server in Next.js and passing the hostname and port to the next function, Next.js automatically builds the request URL based on the provided hostname and port. This behavior is required when using middleware with a custom server.

    However, there is a specific consideration when providing the hostname value. If you provide the complete URL including the protocol (e.g., https://www.txc.com), Next.js may include the port as part of the pathname in the parsed URL object.

    To avoid this issue, you can pass only the hostname without the protocol (e.g., www.txc.com) to the next function. By providing just the hostname, Next.js will correctly handle the request URL and ensure that the pathname does not include the port.

    const next = require('next');
    const app = next({ hostname: 'www.txc.com', dev, port });

    By passing only the hostname (www.txc.com) without the protocol, the issue of including the port in the pathname should be resolved.


  2. you can make use of the req.headers.host property.

     const protocol = req.headers['x-forwarded-proto'] || req.protocol
     const host = req.headers.host
    
     // Construct the base URL without the port number
     const baseUrl = `${protocol}://${host}`
    
     // Construct the full URL including the pathname
     const fullUrl = `${baseUrl}${req.originalUrl}`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search