Giter Club home page Giter Club logo

next-absolute-url's Introduction

next-absolute-url

Get the protocol and host for the absolute URL of your Next.js app (and optionally set a dev url)

This module enables you to easily get the protocol and host of your Next.js app, both on the server and the client. Optionally, you can set a localhost variable, which is useful for local development if you have local lambda functions running on a different port.

Usage

I'm honored that an excellent blog post has been published about this package. For detailed usage, please see: https://web.archive.org/web/20211110110818/https://codeconqueror.com/blog/get-the-current-url-in-next-js/

import absoluteUrl from 'next-absolute-url'
const { protocol, host } = absoluteUrl(req, 'localhost:8004')
const apiURL = `${protocol}//${host}/api/job.js`

or if you just want the full URL origin:

import absoluteUrl from 'next-absolute-url'
const { origin } = absoluteUrl(req)
const apiURL = `${origin}/api/job.js`

If you deployed your Next.js app with now the apiURL will be something like https://your-app.now.sh/api/job.js.

However, if you are running the app locally the apiURL will be http://localhost:8004/api/job.js instead.

Install

With npm installed, run

npm install next-absolute-url

MIT

next-absolute-url's People

Contributors

abhishekshahj avatar armandabric avatar dependabot[bot] avatar dprgarner avatar fdiskas avatar halkeye avatar jakeburden avatar jerrygreen avatar relferreira avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

next-absolute-url's Issues

ReferenceError: req is not defined

I'm running into this error when I try to add this via npm as a package, as well as tried the guide on https://codeconqueror.com/blog/get-the-current-url-in-next-js listed in the README.

Since the npm package wasn't working for me, the following is from the guide to manually troubleshoot it. From what I understand, it should be checking for 'req' under the host variable in the absolute-url file, else do 'window.location.host' but not having much luck.

I'm new to React/Next.js so it's probably something simple I overlooked but would be appreciative if someone can look at this.

// PROJECT/lib/absolute-url.js

function absoluteUrl(req, setLocalhost) {
  let protocol = 'https:'
  let host = req
    ? req.headers['x-forwarded-host'] || req.headers['host']
    : window.location.host

  if (host.indexOf('localhost') > -1) {
    if (setLocalhost) host = setLocalhost
    protocol = 'http:'
  }

  return {
    protocol: protocol,
    host: host,
    origin: protocol + '//' + host,
  }
}

// PROJECT/components/layout.js

import absoluteUrl from '../lib/absolute-url'

const { protocol, host } = absoluteUrl(req, 'localhost:3000')

export default function Layout({ children, pageTitle, description, ...props }) {
  return (
    <>
      <CONTENT>
    </>
  )
}

App Engine - absoluteUrl returning localhost:3000

Hi,

I'm trying to use next-absolute-url on Google App Engine and it seems the URL returned by absoluteUrl used into initialProps is always http://localhost:3000 . On localhost for the same call I have the good host value.

Here my sample code :

App.getInitialProps = ({ ctx }: AppContext) => {
  const { protocol, host } = absoluteUrl(ctx.req);
  return {
    pageProps: {
      domain: protocol + "//" + host,
    },
  };
};
export default App;

Cannot read property 'indexOf' of undefined

Cannot read property 'indexOf' of undefined
TypeError: Cannot read property 'indexOf' of undefined
    at absoluteUrl (/node_modules/next-absolute-url/index.js:4:12)

I tried both the 2 param and the 1 param version

I think that line should be changed to:

  var host = req ? (req.headers['x-forwarded-host'] || req.headers['host']) : window.location.host;

so it grabs host if x-forwarded-host is not set.

Not returning host with port on client-side

Hi,
I found that using absoluteUrl in the client-side returns the host without the port information. In my case, it is returning localhost, although it should be localhost:3000.
I think the solution would be changing window.location.hostname to window.location.host

E.g., image

Returns https instead of http if host is 127.0.0.1

The absoluteUrl function returns only http as protocol if host is 'localhost'.
In case of '127.0.0.1' it always returns https.
In some cases we have to use 127.0.0.1 instead of localhost, but that mixes up protocols returned by absoluteUrl.

`now dev` released. updates?

I published this module before now dev was released.
Since now dev is actually being used, it might be time to update this module. But what updates are needed?

#1 is a great suggestion to check req.headers['x-forwarded-host']

The docs can definitely be updated to better compliment the now dev experience.

I'm open to suggestions, issues, and pull request :)

not compatible with getInitialProps ?

I'm getting ReferenceError: window is not defined when I try to use this module in getInitialProps.
I need to do a fetch for my context data, but I can't hard-code the url - hence looking to use next-absolute-url. But this is failing.

import fetch              from 'isomorphic-unfetch';
import absoluteUrl        from 'next-absolute-url';

export default class MyApp extends App {
  static async getInitialProps(ctx) {
    const { origin } = absoluteUrl(ctx.req);
    console.log('origin', origin);
  }
  render() {
    // etc
  }
}

Window is not defined

ReferenceError: window is not defined

export const getStaticProps: GetStaticProps<IProps> = async ({req}) => {
  59 | 
> 60 | const { origin } = absoluteUrl(req);
     |                               ^
  61 | const apiURL = `${origin}/api/job.js`;
  62 | console.log(origin);

Regression?

Hi,

When the following code runs on client side on a remote machine; absoluteUrl returns https despite that the app is just normal http.

const {origin} = absoluteUrl(req)
const p1 = ${origin}/api/vehicles
console.log('absoluteUrl returned: ' + p1)
const p2 = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '') + '/api/vehicles'
console.log('window returned: ' + p2)

image

Not sure because of index.js line 14 :
var protocol = /^localhost(:\d+)?$/.test(host) ? 'http:' : 'https:'

Strange enough, if the next.js app runs on localhost then everything seems fine.

Improve documentation

next-absolute-url is starting to gain increased usage ๐ŸŽ‰ ๐Ÿ’ฏ

  • npm weekly downloads: 4,903
  • used by: 91 public repos
  • used by: 12 npm packages

Small numbers, but the trend is going upwards ๐Ÿ“ˆ

I'd love to update the README.md with better documentation, such as a full example of it being used in a Next.js page โœ๏ธ

However, I don't have a ton of extra time on my hands at the moment. If anyone would like to help, I would be extremely joyous and grateful. โณ

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.