Skip to content

Commit

Permalink
Replace/Rename Astro.canonicalURL with new Astro.url helper (#3959)
Browse files Browse the repository at this point in the history
* add Astro.url

* Add examples of how to create the canonicalURL

Co-authored-by: Matthew Phillips <matthew@skypack.dev>
  • Loading branch information
FredKSchott and matthewp authored Jul 21, 2022
1 parent d503c5b commit ddefb17
Show file tree
Hide file tree
Showing 35 changed files with 101 additions and 117 deletions.
5 changes: 5 additions & 0 deletions .changeset/unlucky-panthers-yawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Deprecate Astro.canonicalURL, in favor of Astro.url instead.
5 changes: 5 additions & 0 deletions .changeset/yellow-drinks-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Add Astro.url helper for getting the request URL
1 change: 1 addition & 0 deletions examples/blog-multiple-authors/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ import preact from '@astrojs/preact';
export default defineConfig({
// Enable the Preact integration to support Preact JSX components.
integrations: [preact()],
site: `http://astro.build`
});
3 changes: 1 addition & 2 deletions examples/blog-multiple-authors/src/layouts/post.astro
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
---
import MainHead from "../components/MainHead.astro";
import Nav from "../components/Nav.astro";
import authorData from "../data/authors.json";
const { content } = Astro.props;
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<html lang={content.lang || "en"}>
Expand Down
2 changes: 1 addition & 1 deletion examples/blog-multiple-authors/src/pages/about.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Nav from "../components/Nav.astro";
let title = "About";
let description = "About page of an example blog on Astro";
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<html lang="en">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export async function getStaticPaths() {
const { allPosts } = Astro.props;
const title = "Don’s Blog";
const description = "An example blog on Astro";
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
/** filter posts by author, sort by date */
const posts = allPosts
Expand All @@ -28,7 +29,7 @@ const author = authorData[posts[0].frontmatter.author];
{title}
{description}
image={posts[0].frontmatter.image}
canonicalURL={Astro.canonicalURL.toString()}
canonicalURL={canonicalURL.toString()}
/>

<style lang="scss">
Expand Down
2 changes: 1 addition & 1 deletion examples/blog-multiple-authors/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import authorData from "../data/authors.json";
// All variables are available to use in the HTML template below.
let title = "Don’s Blog";
let description = "An example blog on Astro";
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Data Fetching: List all Markdown posts in the repo.
let allPosts = await Astro.glob("./post/*.md");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function getStaticPaths({ paginate, rss }) {
// page
const title = "Don’s Blog";
const description = "An example blog on Astro";
const { canonicalURL } = Astro;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const { page } = Astro.props;
---

Expand Down
1 change: 1 addition & 0 deletions examples/blog/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ import preact from '@astrojs/preact';
// https://astro.build/config
export default defineConfig({
integrations: [preact()],
site: `http://astro.build`
});
5 changes: 3 additions & 2 deletions examples/blog/src/components/BaseHead.astro
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface Props {
description: string;
}
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const { title, description } = Astro.props;
---

Expand All @@ -21,14 +22,14 @@ const { title, description } = Astro.props;

<!-- Open Graph / Facebook -->
<meta property="og:type" content="website" />
<meta property="og:url" content={Astro.canonicalURL} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content="https://astro.build/social.png" />

<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:url" content={Astro.canonicalURL} />
<meta property="twitter:url" content={canonicalURL} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
<meta property="twitter:image" content="https://astro.build/social.png" />
Expand Down
1 change: 1 addition & 0 deletions examples/docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export default defineConfig({
// Enable React for the Algolia search component.
react(),
],
site: `http://astro.build`
});
4 changes: 3 additions & 1 deletion examples/docs/src/components/HeadSEO.astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ export interface Props {
site: any;
canonicalURL: URL | string;
}
const { content = {}, canonicalURL } = Astro.props;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const { content = {} } = Astro.props;
const formattedContentTitle = content.title ? `${content.title} 🚀 ${SITE.title}` : SITE.title;
const imageSrc = content?.image?.src ?? OPEN_GRAPH.image.src;
const canonicalImageSrc = new URL(imageSrc, Astro.site);
Expand Down
5 changes: 3 additions & 2 deletions examples/docs/src/layouts/MainLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ import RightSidebar from "../components/RightSidebar/RightSidebar.astro";
import * as CONFIG from "../config";
const { content = {} } = Astro.props;
const currentPage = new URL(Astro.request.url).pathname;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const currentPage = Astro.url.pathname;
const currentFile = `src/pages${currentPage.replace(/\/$/, "")}.md`;
const githubEditUrl = CONFIG.GITHUB_EDIT_URL && CONFIG.GITHUB_EDIT_URL + currentFile;
---

<html dir={content.dir ?? "ltr"} lang={content.lang ?? "en-us"} class="initial">
<head>
<HeadCommon />
<HeadSEO {content} canonicalURL={Astro.canonicalURL} />
<HeadSEO {content} canonicalURL={canonicalURL} />
<title>{content.title ? `${content.title} 🚀 ${CONFIG.SITE.title}` : CONFIG.SITE.title}</title>
<style>
body {
Expand Down
24 changes: 18 additions & 6 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,29 @@ export interface BuildConfig {
* [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global)
*/
export interface AstroGlobal extends AstroGlobalPartial {
/** Canonical URL of the current page. If the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option is set, its origin will be the origin of this URL.
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrocanonicalurl)
/**
* Canonical URL of the current page.
* @deprecated Use `Astro.url` instead.
*
* Example:
* ```astro
* ---
* const canonicalURL = new URL(Astro.url.pathname, Astro.site);
* ---
* ```
*/
canonicalURL: URL;
/** The address (usually IP address) of the user. Used with SSR only.
*
*/
clientAddress: string;
/**
* A full URL object of the request URL.
* Equivalent to: `new URL(Astro.request.url)`
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#url)
*/
url: URL;
/** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
*
* Example usage:
Expand Down Expand Up @@ -224,11 +238,9 @@ export interface AstroGlobalPartial {
/**
* Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option
*
* If `site` is undefined, the URL object will instead be built from `localhost`
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite)
*/
site: URL;
site: URL | undefined;
}

type ServerConfig = {
Expand Down
6 changes: 1 addition & 5 deletions packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,7 @@ export const AstroConfigSchema = z.object({
.string()
.url()
.optional()
.transform((val) => (val ? appendForwardSlash(val) : val))
.refine((val) => !val || new URL(val).pathname.length <= 1, {
message:
'"site" must be a valid URL origin (ex: "https://example.com") but cannot contain a URL path (ex: "https://example.com/blog"). Use "base" to configure your deployed URL path',
}),
.transform((val) => (val ? appendForwardSlash(val) : val)),
base: z
.string()
.optional()
Expand Down
30 changes: 21 additions & 9 deletions packages/astro/src/core/render/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
import { renderSlot } from '../../runtime/server/index.js';
import { LogOptions, warn } from '../logger/core.js';
import { isScriptRequest } from './script.js';
import { createCanonicalURL, isCSSRequest } from './util.js';
import { isCSSRequest } from './util.js';

const clientAddressSymbol = Symbol.for('astro.clientAddress');

Expand Down Expand Up @@ -109,16 +109,10 @@ class Slots {

let renderMarkdown: any = null;

function isPaginatedRoute({ page }: { page?: Page }) {
return page && 'currentPage' in page;
}

export function createResult(args: CreateResultArgs): SSRResult {
const { markdown, params, pathname, props: pageProps, renderers, request, resolve, site } = args;
const { markdown, params, pathname, props: pageProps, renderers, request, resolve } = args;

const paginated = isPaginatedRoute(pageProps);
const url = new URL(request.url);
const canonicalURL = createCanonicalURL('.' + pathname, site ?? url.origin, paginated);
const headers = new Headers();
if (args.streaming) {
headers.set('Transfer-Encoding', 'chunked');
Expand Down Expand Up @@ -155,7 +149,6 @@ export function createResult(args: CreateResultArgs): SSRResult {

const Astro = {
__proto__: astroGlobal,
canonicalURL,
get clientAddress() {
if (!(clientAddressSymbol in request)) {
if (args.adapterName) {
Expand All @@ -174,6 +167,7 @@ export function createResult(args: CreateResultArgs): SSRResult {
params,
props,
request,
url,
redirect: args.ssr
? (path: string) => {
return new Response(null, {
Expand Down Expand Up @@ -220,6 +214,24 @@ ${extra}`
slots: astroSlots,
} as unknown as AstroGlobal;

Object.defineProperty(Astro, 'canonicalURL', {
get: function() {
warn(args.logging,
'deprecation',
`${bold(
'Astro.canonicalURL'
)} is deprecated! Use \`Astro.url\` instead.
Example:
---
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---
`
);
return new URL(this.request.url.pathname, this.site);
},
});

Object.defineProperty(Astro, '__renderMarkdown', {
// Ensure this API is not exposed to users
enumerable: false,
Expand Down
12 changes: 0 additions & 12 deletions packages/astro/src/core/render/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,6 @@ import npath from 'path-browserify';
import type { ModuleNode, ViteDevServer } from 'vite';
import type { Metadata } from '../../runtime/server/metadata.js';

/** Normalize URL to its canonical form */
export function createCanonicalURL(url: string, base?: string, paginated?: boolean): URL {
let pathname = url.replace(/\/index.html$/, ''); // index.html is not canonical
// Only trim the first page's /1 param if Astro's paginated() was used
if (paginated) {
pathname = pathname.replace(/\/1\/?$/, ''); // neither is a trailing /1/ (impl. detail of collections)
}
if (!npath.extname(pathname)) pathname = pathname.replace(/(\/+)?$/, '/'); // add trailing slash if there’s no extension
pathname = pathname.replace(/\/+/g, '/'); // remove duplicate slashes (URL() won’t)
return new URL(pathname, base);
}

/** Check if a URL is already valid */
export function isValidURL(url: string): boolean {
try {
Expand Down
10 changes: 0 additions & 10 deletions packages/astro/src/core/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,6 @@ export function createRequest({
});

Object.defineProperties(request, {
canonicalURL: {
get() {
warn(
logging,
'deprecation',
`Astro.request.canonicalURL has been moved to Astro.canonicalURL`
);
return undefined;
},
},
params: {
get() {
warn(logging, 'deprecation', `Astro.request.params has been moved to Astro.params`);
Expand Down
8 changes: 4 additions & 4 deletions packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,19 +516,19 @@ function createAstroGlobFn() {
// Inside of getStaticPaths.
export function createAstro(
filePathname: string,
_site: string,
_site: string | undefined,
projectRootStr: string
): AstroGlobalPartial {
const site = new URL(_site);
const url = new URL(filePathname, site);
const site = _site ? new URL(_site) : undefined;
const referenceURL = new URL(filePathname, `http://localhost`);
const projectRoot = new URL(projectRootStr);
return {
site,
fetchContent: createDeprecatedFetchContentFn(),
glob: createAstroGlobFn(),
// INVESTIGATE is there a use-case for multi args?
resolve(...segments: string[]) {
let resolved = segments.reduce((u, segment) => new URL(segment, u), url).pathname;
let resolved = segments.reduce((u, segment) => new URL(segment, u), referenceURL).pathname;
// When inside of project root, remove the leading path so you are
// left with only `/src/images/tower.png`
if (resolved.startsWith(projectRoot.pathname)) {
Expand Down
4 changes: 1 addition & 3 deletions packages/astro/src/vite-plugin-astro/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ async function compile({
// For Windows compat, prepend the module ID with `/@fs`
pathname: `/@fs${prependForwardSlash(moduleId)}`,
projectRoot: config.root.toString(),
site: config.site
? new URL(config.base, config.site).toString()
: `http://localhost:${config.server.port}/`,
site: config.site?.toString(),
sourcefile: filename,
sourcemap: 'both',
internalURL: `/@fs${prependForwardSlash(
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/test/astro-get-static-paths.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ describe('getStaticPaths - numeric route params', () => {

const canonical = $('link[rel=canonical]');
expect(canonical.attr('href')).to.equal(
`https://mysite.dev/posts/${page}/`,
`doesn't trim the /${page}/ route param`
`https://mysite.dev/posts/${page}`,
`doesn't trim the /${page} route param`
);
}
});
Expand Down
Loading

0 comments on commit ddefb17

Please sign in to comment.