How to create dynamic routes that start with a specific character in Next.js? - next.js

I want to create routes that start with # symbol how should I structure the pages folder?
first I tried to create a folder with # as its name however it will create routes that proceed with # like www.example.com/#/something. I even tried [#topic] and #[topic] names for folders but it does not work as expected.
I want to have routes like:
www.example.com/#computer
www.example.com/#music
www.example.com/#programming
how can I approach the problem?
My Next.js version is 9.2.1

If you don't want to have a custom server, try rewrites and some regex. Next.js uses path-to-regexp under the hood.
async rewrites() {
return [
{
source: '/:userId(#[a-zA-Z0-9]+)/:id*',
destination: "/user/:userId/:id*",
}
]
}
You still will have to sprinkle
<Link href="/user/[userId]" as=`#${userId}`/>
as mentioned by other posters.

You should just change the as prop of the Link component adding the # symbol in the place you need it.
For example, if you keep you routes/structure like the example for dynamic routing provided by Next.js, changing the index.js under pages/post/[id]/ to the following:
import { useRouter } from 'next/router'
import Link from 'next/link'
import Header from '../../../components/header'
const Post = () => {
const router = useRouter()
const { id } = router.query
return (
<>
<Header />
<h1>Post: {id}</h1>
<ul>
<li>
<Link
href="/post/[id]/[comment]"
as={`/post/#${id}/first-comment`}>
<a>First comment</a>
</Link>
</li>
</ul>
</>
)
}
export default Post
will give you a URL like this: http://localhost:3000/post/#first/first-comment
I hope this helps you find your way.

As #Nico mentioned, We can approach the solution with inspiring from custom-server example in Next.js repo.
Page's structure will be like this: page->[topic]
We need to check inside server.js for any incoming request with URL that starts with # symbol, to do so we'll get help regular expressions inside express.js:
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// this will match all the URLs that start with #
// e.g. #computer, #hello
server.get('/#*', (req, res) => {
return app.render(req, res, '/[topic]', req.query)
})
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
This simply coordinates requests that start with # to [topic] component as before as handling other routes.
Inside component for client-side it is as simple as this:
<Link href="/[topic]" as=`#${topicString}`/>
You can get topicString in different ways like using query inside getInitialProps

Related

Headers are removed from middleware in production Next js

I have such a strange thing. Project on next js 12.3. I use middleware to add canonical link to headers. Everything works locally, and the required headers are added, but when deployed in production, the header I need is not added.
if the subdomain is not www, the canonical must be a link to the www version
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest, res: NextResponse) {
const { protocol, href } = req.nextUrl;
const subdomain = href.replace('https://','').split('.')[0];
if (subdomain !== 'www') {
const urlArr = href?.split('//');
const afterSubdomainUrl = urlArr?.slice(1, urlArr.length)?.join('//');
const response = NextResponse.next();
response.headers.append(
'Link',
`<${protocol}//www.${afterSubdomainUrl}>; rel="canonical"`,
);
return response;
}
}
The problem was at DockerFile - need to implement next code at
app/Dockerfile
COPY middleware.ts /app/middleware.ts
RUN true

Next.js: How to access geolocation information provided by middleware.js?

The Next.JS middleware feature allows for easy adding of geolocation based information to a request:
// /middleware.js
import { NextResponse } from 'next/server'
export function middleware(req) {
const { nextUrl: url, geo } = req
const country = geo.country || 'DE'
url.searchParams.set('country', country)
return NextResponse.rewrite(url)
}
How do I access this information from the code of a page? I am sure there is an easy way, and I was just not able to find it...
I just found a straight-forward solution.
Make sure /pages/_app.js has the following lines in it (default if created with npx create-next-app):
// /pages/_app.js
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Then the country (or other information added by the NextJS middleware can be accessed directly like this:
let geoCountry = pageProps.country;

How to use runtime config in composable?

I want to do this
composables/apiFetch.ts
import { $fetch } from 'ohmyfetch'
export const useApiFetch = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
And use it within Pinia so I don't repeat myself writing $fetch.create over and over again for every single API call.
somewhere_in_pinia.ts
...TRIM...
actions: {
async doSomething(payload: SomeNicePayload): Promise<void> {
const response = await useApiFetch('/something', { method: 'POST', body: payload })
}
}
...TRIM...
But Nuxt won't allow me
[nuxt] [request error] nuxt instance unavailable
at useNuxtApp (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:472:13)
at Module.useRuntimeConfig (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:480:10)
at $id_Yl353ZXbaH (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:38358:90)
at async __instantiateModule__ (/D:/XXXX/frontend/prms-fe/.nuxt/dist/server/server.mjs:40864:3)
I have been looking for solution online, followed instruction from the official discussion to no avail.
EDIT
I don't want to use Nitro, since my backend is already written on Laravel. I need to access the host without re-typing it all over the place so I thought I could use .env and runtimeConfig.
you are trying to access Nuxt instance while it's not ready yet. To make it work, write your composable as a function :
import { $fetch } from 'ohmyfetch'
export const useApiFetch = (url, params) => {
const instance = $fetch.create({ baseURL: useRuntimeConfig().apiUrl })
return instance(url, params)
}

Get values from SvelteKit's $app/stores outside of the lifecycle of a component

My Svelte components import readable stores like this:
import { classes, locations, schedule } from 'stores.ts'
In stores.ts, I want to build the URL for fetch dynamically using page.host from $app/stores.
// Note: this is not a Svelte component; it's stores.ts
import { readable } from 'svelte/store'
import { getStores } from '$app/stores'
const { page } = getStores()
let FQDN
page.subscribe(({ host }) => {
FQDN = host
})
const getArray = async (url) => {
const response: Response = await fetch(url)
if (!response.ok) throw new Error(`Bad response trying to retrieve from ${url}.`)
return await response.json()
}
const getReadableStore = (url: string) => readable([], set => {
getArray(`http://${FQDN}${url}`)
.then(set)
.catch(err => console.error('Failed API call:', err))
return () => {}
})
export const classes = getReadableStore('/api/class/public.json')
export const locations = getReadableStore('/api/location/public.json')
export const schedule = getReadableStore('/api/schedule/public.json')
The sixth line throws this error...
Error: Function called outside component initialization
at get_current_component (/Users/nates/dev/shy-svelte/node_modules/svelte/internal/index.js:652:15)
at Proxy.getContext (/Users/nates/dev/shy-svelte/node_modules/svelte/internal/index.js:685:12)
at Module.getStores (/.svelte-kit/dev/runtime/app/stores.js:17:26)
at eval (/src/stores.ts:6:38)
at instantiateModule (/Users/nates/dev/shy-svelte/node_modules/#sveltejs/kit/node_modules/vite/dist/node/chunks/dep-e9a16784.js:68197:166)
Two questions...
What is the correct way to get page values from $app/stores outside of the context of a component? Is this possible? Answer from below: No, this is not possible outside the context of a component.
If I'm accessing a SvelteKit site, let's say http://localhost:3000/something or https://example.com and a Svelte component loads a readable store from stores.ts, is there a way in stores.ts to determine whether the original page request that loaded the component (which loaded from stores.ts) was http or https? Answer from below: No, this is not possible in stores.ts - only from a component.
UPDATE: Based on the feedback, I'm going to set a value in my .env called VITE_WEB_URL=http://localhost:3000 and change it for the production system. This cuts down on the number of lines of code and may be a better practice (comments welcome)...
// revised stores.ts
import { readable } from 'svelte/store'
const { VITE_WEB_URL } = import.meta.env
const getArray = async (url) => {
const response: Response = await fetch(url)
if (!response.ok) throw new Error(`Bad response trying to retrieve from ${url}.`)
return await response.json()
}
const getReadableStore = (url: string) => readable([], set => {
getArray(`${VITE_WEB_URL}${url}`)
.then(set)
.catch(err => console.error('Failed API call:', err))
return () => {}
})
export const classes = getReadableStore('/api/class/public.json')
export const locations = getReadableStore('/api/location/public.json')
export const schedule = getReadableStore('/api/schedule/public.json')
Extract from https://kit.svelte.dev/docs#modules-$app-stores
Because of that, the stores are not free-floating objects: they must be accessed during component initialisation, like anything else that would be accessed with getContext.
Therefore, since the readable store is bound to the context of a svelte component, I suggest you subscribe either way ($ or .subscribe) inside the component of the SvelteKit website and then send the protocol value (http or https) as parameter when it updates so that stores.ts stores it in a variable.
However, it looks like SvelteKit does not provide the protocol value, so parse the client side window.location.href in the page subscription and then send it.
Referencing a svelte store can be done everywhere.
Using the $: shorthand syntax, however, only works within a component.
$: BASE = `http://${$page.host}`
SvelteKit appears to delegate this to fetch indeed

getStaticPath and the need for filetype in the URL

In /pages I have [page].js and index.js.
[page].js generate needed Pages by the Value of "CustomPage". It's content comes from an Data-JSON-File.
It work like expected, as long as I start on the Homepage and use links inside of my Webpage.
For example I have 2 Pages for now: /impressum and /datenschutz.
So clicking the link "Impressum" open myDomain.com/impressum (and it work, BUT notice, there is no .html at the end).
BUT, if I refresh the page, or type myDomain.com/impressum directly in the addressbar of the browser, I got an not found error (from nginx-server, not from next!).
Second try
As I need a fully static page and I've added getStaticPath and getStaticProps in the file for testing purposes, so that "real" html-files will be created:
import { useRouter } from 'next/router';
import Index from './index';
import config from '../content/config.yml';
import CustomPage from '../src/components/CustomPage';
const RoutingPage = () => {
const { customPages } = config;
const router = useRouter();
const { page } = router.query;
const findMatches = (requestedPage) =>
customPages.find((customPage) => customPage.name === requestedPage) ||
false;
const customPageData = findMatches(page);
if (customPageData !== false) {
return <CustomPage pageContext={customPageData} />;
}
return page === 'index' ? (
<Index page={page} />
) : (
<p style={{ marginTop: '250px' }}>whats up {page}</p>
);
};
export async function getStaticPaths() {
return {
paths: [
{ params: { page: 'impressum' } },
{ params: { page: 'datenschutz' } },
],
fallback: false, // See the "fallback" section below
};
}
export async function getStaticProps({ params }) {
return { props: { page: params.page } };
}
export default RoutingPage;
This generates the single pages as real html-files:
But this lead me to the next issue:
I've implemented internal Links in the Webpage like this:
which still lead a user to myDomain.com/impressum, now additionally there is myDomain.com/impressum.html available. From SEO perspective, this are two different paths.
How do I get them unified, so that I have only one path - regardles of whether if I open it from within my Webpage, or enter it directly.
Workaround Idea (??)
Sure, I could everywhere use something like:
<Link href={`/${item.page}.html`}>
But this only work if the Page is exported and copied to the Server. For next dev and next start this won't work, because the .html-File don't exist.... and so I'll lost the "page preview" while working at the page.
So only Idea I have is to set an ENV-Variable for .env.development & .env.production and encapsulate the -Component from NEXT in a HOC.
In that HOC I could check if I'm currently in dev or prod and don't use .html for those links... otherwise add the .html to the link.
What YOU say about this. Do you have any other solution?
I don't know if it's state of the art, but as little workaround I did this:
I place the next/link-Component in a HOC and check if it's run on development or production (process.env.NODE_ENV):
import React from 'react';
import Link from 'next/link';
const LinkHoc = (props) => {
const { as, href, children } = props;
if (process.env.NODE_ENV === 'production') {
return (
<Link
{...props}
as={as ? `${as}.html` : ''}
href={href ? `${href}.html` : ''}
/>
);
}
return <Link {...props}>{children}</Link>;
};
export default LinkHoc;
With this workaround you get mydomain.com/impressum links in DEV and mydomain.com/impressum.html in production.
Only thing what to do at least is to rename the JSON-Files for the generated pages.
They are in /out/_next/data/XYZranadomString/.
They are named like impressum.json and you need to rename it to impressum.html.json to fix the 404 error on clientside for this files.
Would love to see a better Solution, so if you have any suggestions, please let me know!

Resources