How to create a dynamic url with the # symbol - javascript

How would I create a dynamic route in Next.js with the # symbol?
For example localhost:3000/#some_username
I know you can create dynamic routes within the pages folder but how would I do it with just the # symbol and no / afterward like the above example.

You can add a prefix by defining a rewrite in your next.config.js.
module.exports = {
async rewrites() {
return [
{
source: '/#:username',
destination: '/users/:username'
}
]
}
}
This redirects all /#{username} routes to /users/{username}.
Some more information about rewrites in nextjs can be found here

It's the same as the standard dynamic routing in Next.js. You don't need rewrites.
Name the file or folder [#:username] in your root directory.
There are a few ways to do this:
App directory as folder named [#:username]
/app/[#:username]/page.js
Pages directory as file named [#:username].js
/pages/[#:username].js
Pages directory as folder named [#:username]
/pages/[#:username]/index.js
The param can be access the query param on the page like
import { useRouter } from "next/router";
const { query } = useRouter();
const username = query["#:username"];

Related

How to add a static route after a dynamic one in ExpressJS?

There are two 2 files with routes.
user.route.js
router.get('/user/:id');
user-transaction.js
router.get('/user/transaction');
My architecture looks like this:
src/
user/user.route.js
user-transaction/user-transaction.route.js
I connect all my routes in the project in the following way:
const dirs = await recursive(dir);
dirs.forEach((res) => {
if (res.includes('route')) {
console.log(res);
const path = `#modules/${res}}`;
router.use(require(path));
}
});
The problem is that Express doesn't see the /user/transaction route because it connects later than /user/:id and thinks /user/transaction refers to /user/:id.
It seems logical to just move the route higher, but I connect the routes dynamically. That is, it simply takes the files in order and connects the routes in the same order. Is there a solution to this problem or will I have to manually connect all the routes?

Optional dynamic route without a custom server - NextJS - 9.5.2

I am trying to create localized routes with optional first param like /lang?/../../, but without a custom server.
From 9.5 NextJS has this option dynamic optionall parameters, if you set the folder or a file with a name:
[[...param]]. I did that.
The problem is that, i have other routes and I want all of them to be with that lang prefix, ut optional with default language, if that lang is not provided
I have a folder [[...lang]] with a file index.js, with simple function component just for testing. Now optional parameter works for the home page / and /en, but I have other files, which I want to be with that optional lang. For the example, I have about.js and I want to access it via /en/about and /about.
I can't put about.js inside [[...lang]], because, I am getting an error:
Failed to reload dynamic routes: Error: Catch-all must be the last part of the URL.
I know what it says and why is that, but I have a fixed collection of languages ['en', 'fr'] and I can check is there a lang.
Is there a way, without a custom server to use optionally a dynamic first part of the path, like
/en/about and /about ?
I think you are talking about this feature. Have a look on this https://nextjs.org/blog/next-9-5#support-for-rewrites-redirects-and-headers
To extend the answer from #Vibhav, in next.config.js:
const nextConfig = {
async rewrites(){
return [
// URLs without a base route lang param like /my-page
{
source: '/',
destination: '/'
},
// URLs with a base route lang param like /en/my-page
{
source: '/:lang*/:page*',
destination: '/:page*'
},
// URLs `/en/post/post_id`
{
source: '/:lang/:path/:page',
destination: '/:path/:page'
},
]
}
};
module.exports = withBundleAnalyzer(nextConfig);
all pages are in the pages folder. Not the best solution for now, because it works in a deep up to like /pages/another-folder/file.
You can even get the lang param in your pages or _app.js:
....
const router = useRouter();
if(router.query.lang){
pageProps.lang = router.query.lang;
}
console.log(pageProps.lang);
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
For URL - /en/my-page, router.query.lang will be equal to en.
For URL - /my-page, router.query.lang will be undefined, but you can set a default lang.

Import JS file placed in /public into JS file in /src

I am currently working on implementing OAuth authentication into my Vue app.
The authentication logic consists out of two files, the src/auth.js and public/silent-renewal.html. The first file contains all the logic to interact with the OAuth server. The second file is used to process the callback when the access token is renewed in the background.
In addition to these two files there is the file public/oidc-settings.js. This file contains a JSON variable defining the settings for the OAuth server.
It defines a JSON variable with the settings and a method to access them:
const settings = {
authority: 'http://localhost:8180/auth/realms/auth-example',
client_id: 'webclient-service',
redirect_uri: 'http://localhost:8080/callback',
response_type: 'code',
response_mode: 'query',
scope: 'openid profile',
post_logout_redirect_uri: 'http://localhost:8080/logout',
silent_redirect_uri: 'http://localhost:8080/silent-renewal.html',
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true
}
function getSettings () {
return settings
}
In the silent-renewal.html file I access the settings by importing them with a script tag (<script src='oidc-settings.js'></script.
The problem is that I don't know how to access the oidc-settings.js from my auth.js. Currently I define the exact same settings again in the auth.js file.
How can I import a Javascript file placed in the public folder of my application into a Javascript file in the src folder?
If you're asking how you can navigate into a different folder, you can navigate up one level of a folder using ../.
It would look like this: '../public/your-file.js'
If you need to navigate up two (or more), just add another ../ for each level like this '../../folder/file.js'
You are trying to import something that is not set to be imported, probably your path is correct but you need to make the function that returns the configuration accessible to be imported.
Just change your settings file , so your function getSetting can be imported
export const getSettings = () => {
return settings
}
then in your "src" file just
import { getSettings } from '../public/../../'

Subroutes in Next Js

I´m new to next js, I have created a file called orders.js under pages directory, and I can access it correctly from localhost:3000/orders.
However, I want now to have a subroute, to access the order with id 1 (for example). So I have created a directory 'orders' inside the directory pages, and renamed order.js to index.js, after that, I have created another file inside the orders directory called id.js.
So my current structure is:
pages/
orders/
index.js
id.js
However I cannot access to localhost:3000/orders/1.
Using Nuxt js, this was trivial, how can I achieve the same with next.js ?
Thanks
This is also trivial with Nextjs, however, you're trying to achieve it the harder way.
Your first approach is correct. If you don't specify a route for your pages in the server.js file, Nextjs will automatically use them if the URL is correct (in this case orders leads to the orders.js page).
What you're looking for is to create a custom route. You can see the documentation for this here
I find the example in the documentation confusing, so I recommend using express instead. Here's an example for that. You can then see the express routes in the server.js file of the example.
Your route would end up looking something like this:
server.get('/orders/:id', (req, res) => {
return app.render(req, res, '/orders', req.query)
})
Where :id is a query param which you can then access in your getInitialProps inside your orders.js page.
You can check the express routing examples in the express documentation.
You can try using next-routes, dynamic routes for Next.js
And simply create a routes.js and add,
const routes = require('next-routes')
module.exports = routes()
.add('orders', '/orders/:id', 'orders/id')
// name, url, page folder
Or if you only want the server side routing,
server.get('/orders/:id', (req, res) => {
const actualPage = '/orders'
app.render(req, res, actualPage, req.query)
})
This might help you : https://nextjs.org/docs#dynamic-routing.
by adding [ ] to a page it creates a dynamic route, in this case [orderid].js can be used to map multiple orders to a single page.
pages/
orders/
[id].js
use
pages/
orders/
[dynamic_subroute].js
now catch it with
const router = useRoute();
const { dynamic_subroute } = router.query;
Now, you can catch the value (any) dynamically from the url which is used instead of dynamic_subroute
like- if the url is pages/orders/1
then value of dynamic_subroute will be 1 in your page

Access static resource in server-side code in NextJs?

Im using the static render feature of NextJS to generate a static version of my site thus I want to ensure that on the very first render of the page all the data it needs to render correctly is supplied.
I have a number of blog posts which I have stored as .md files in /static and want to access them in a page such as:
import * as fs from "fs";
...
export default class extends React.Component<IProps, any> {
static async getInitialProps (props: IServerProps) {
const post = (await getDb()).posts.find(p => p.id == props.query.id);
const markdown = fs.readFileSync(`/static/posts/${post.markdownFileName}`);
return { post, markdown }
}
...
But if try to run the above I get the following error:
This dependency was not found: * fs
So im not sure how I should go about accessing these static resources while on the server..
Unfortunately Next.js doesn't allow the use of webpack loaders to handle different file types on the server (Although they are used to build the client-side bundles), but it is possible to use a Babel plugin. One such plugin for Markdown content can be found here: https://www.npmjs.com/package/babel-plugin-markdown
After configuring it in .babelrc:
{
"plugins": ["markdown"]
}
it's possible to use markdown.require() to pull in .md content:
const html = markdown.require('./foo.md')
More options are described at the link!

Categories

Resources